依赖pom.xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
1.json字符串转换JSONObject/JSONArray
String jsonTemplate1="{\"taskIds\":[\"c072a9a8-2275-11eb-a135-d83bbfb92464\",\"eea5b550-2274-11eb-a135-d83bbfb92464\"],\"processIds\":[\"bf827d36-2275-11eb-a135-d83bbfb92464\",\"ee1ab34e-2274-11eb-a135-d83bbfb92464\"],\"formProperty\":{\"comfirmWarning\":0}}";
JSONObject paramsBody = JSONObject.parseObject(jsonTemplate1);
JSONArray taskIds = ((JSONArray) paramsBody.get("taskIds"));
JSONArray processIds = (JSONArray) paramsBody.get("processIds");
JSONObject params = (JSONObject) paramsBody.get("formProperty");
for(int i=0;i<taskIds.size();i++) {
String taskId = taskIds.get(i)!=null?taskIds.get(i).toString():"";
System.out.println(taskId);
}
System.out.println(params.toString());
2.json字符串转换为对象
String jsonUser="{\n" +
"\"name\":\"肖战\",\n" +
"\"sex\":\"男\",\n" +
"\"age\":30\n" +
"}";
User parseUserObject = JSONObject.parseObject(jsonUser, User.class);
System.out.println(parseUserObject);
3.Map转换为JSONObject对象
Map resultMap=new HashMap();
resultMap.put("name","zhangsan");
resultMap.put("age","18");
//方法1 先转换为json串 后转换为JSONObject对象
String json = JSON.toJSONString(resultMap);
JSONObject jsonObject = JSON.parseObject(json);
System.out.println(jsonObject);
//方法2 直接转换
String x =JSONObject.toJSONString(resultMap);
System.out.println(x);