//1.json的简单格式{"name":"lisi","age",12}
String json1 = "{'name':'lisi','age':12}";
//解析1
JSONObject json1Obj = JSONObject.parseObject(json1);
String name = json1Obj.get("name").toString();
System.out.println(name);//lisi
//解析2
Map<String,Object> json1Map = (Map<String, Object>) JSONObject.parseObject(json1, Map.class);
String name2 = json1Map.get("name").toString();
System.out.println(name2);//lisi
//2.json数组格式(含有[]符号,用JsonArray解析)
String json2 = "{'code':'aaa','name':['array1','array2','array3']}";
JSONObject parseObject2 = JSONObject.parseObject(json2);
String code = parseObject2.get("code").toString();
System.out.println(code);//aaa
JSONArray array2 = (JSONArray) parseObject2.get("name");
System.out.println(array2.get(0));//array1
//复杂的json
ArrayList<String> array = new ArrayList<String>();
array.add("array1");
array.add("array2");
array.add("array3");
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("code", "bbb");
map2.put("code2", "bbb");
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", array);
map.put("code", "aaa");
map.put("data", map2);
String jsonString = JSONObject.toJSONString(map);
System.out.println(jsonString);
String ss = "{'code':'aaa','data':{'code':'bbb','code2':'bbb'},'name':['array1','array2','array3']}";
Map<String,Object> parseObject = JSONObject.parseObject(ss, Map.class);
System.out.println(parseObject.toString());//{name=["array1","array2","array3"], data={"code":"bbb","code2":"bbb"}, code=aaa}
Map<String,Object> map3 = (Map<String, Object>) parseObject.get("data");
System.out.println(map3.toString());//{"code":"bbb","code2":"bbb"}
JSONArray arrayList = (JSONArray) parseObject.get("name");
System.out.println(arrayList.toString());//["array1","array2","array3"]
}
fastJson使用demo
最新推荐文章于 2024-07-18 08:38:03 发布