springBoot的jar包路径
<!--处理JSON格式-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
与map转换
// 创建一个JSONObject对象
JSONObject jsonObject1 = new JSONObject();
// Map 与 JSONObject 相互转换
Map<String, String> map1 = new HashMap<String, String>();
map1.put("we", "dsds");
JSONObject jsonObject2 = JSONObject.fromObject(map1);
Map<String, String> map2 = (Map)JSONObject.toBean(jsonObject2, Map.class);
// 字符串 转 JSONObject
JSONObject jsonObject3 = JSONObject.fromObject("{obj: [{name: 'wwp'}, {age: 22}], obj: 2}");
//put() 和 get() 方法
jsonObject2.put("key", "sds");
//注意:如果键不存在,则抛出异常
jsonObject2.get("key");
使用
//创建一个JSONObject对象
JSONObject jsonObject = new JSONObject();
jsonObject.put("key1", "value1");
jsonObject.put("key2", "value2");
jsonObject.put("key3", "value3");
jsonObject.put("key4", "value4");
System.out.println("jsonObject:"+jsonObject);
//创建一个JSONArray对象
JSONArray jsonArray=new JSONArray();
jsonArray.add("value1");
jsonArray.add("value2");
jsonArray.add("value3");
jsonArray.add("value4");
System.out.println("jsonArray:"+jsonArray);
//Map转成JSONObject
Map<String, String> map=new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
map.put("key4", "value4");
System.out.println("jsonObject2:"+JSONObject.fromObject(map));
//List转成JsonArray
List<String> list=new ArrayList<String>();
list.add("value1");
list.add("value2");
list.add("value3");
System.out.println("jsonArray2:"+JSONArray.fromObject(list));
//JsonArray解析map,会将整个json对象放进数组。
System.out.println("jsonArray from map:"+JSONArray.fromObject(map));
//将JSONObject放入JsonArray
JSONObject jsonObject3=new JSONObject();
jsonObject3.put("A", "A1");
jsonObject3.put("B", "B1");
jsonObject3.put("C", "C1");
System.out.println("将JSONObject放入JsonArray:"+JSONArray.fromObject(jsonObject3));