fastjson 快速上手
json字符串取值
1 @Test 2 public void test001(){ 3 String jsonStr = "{'name':'张三','age':22,'sex':'男'}"; 4 //字符串转json对象 5 JSONObject jsonObject = JSONObject.parseObject(jsonStr); 6 String name = jsonObject.getString("name"); 7 Integer age = jsonObject.getInteger("age"); 8 String sex = jsonObject.getString("sex"); 9 System.out.println(name + age + sex ); 10 }
获取json数组的值
@Test public void test(){ String json="{'name':'张三','age':55,'sex':'男','format':[{'province':'上海市','city':'上海市','district':'黄浦区'}]}"; JSONObject jsonObject = JSONObject.parseObject(json); JSONArray format1 = jsonObject.getJSONArray("format"); System.out.println(format1 ); JSONObject jsonObject2 = JSONObject.parseObject(format1.getString(0)); String province = jsonObject2.getString("province"); String city = jsonObject2.getString("city"); String district = jsonObject2.getString("district"); System.out.println(province + city + district ); }
json字符串 转java对象 与 java对象转json字符串,数组用 JSONArray,非数组就用JSONObject
@Test public void test01( ) { String jsonStr2 = "[{'name':'张三','age':23},{'name':'李四','age':500,'address':'杭州市'}]"; List< Users > users = JSONArray.parseArray(jsonStr2, Users.class); System.out.println(users); //还原成json字符串 String jsonStr = JSONArray.toJSONString(users); System.out.println(jsonStr); }
本文来自博客园,作者:lanwf,转载请注明原文链接:https://www.cnblogs.com/lccsdncnblogs/p/fastjson.html