一.json对象转字符串
JSONObject jsonObject = new JSONObject(payload);
jsonObject.toJSONString(0)
二.字符串转json对象
import cn.hutool.json.JSONUtil;
import java.util.Map;
public class JsonToMapExample {
public static void main(String[] args) {
JSONObject payloadJson = new JSONObject(payload);
Map<String, Object> map1 = payloadJson.toBean(new TypeReference<Map<String, Object>>() {});
}
}
三、创建json格式的字符串
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
public class JsonArrayInJsonObjectExample {
public static void main(String[] args) {
// 创建外部的JSONObject
JSONObject outerJsonObject = new JSONObject();
// 为数组内的每个JSON对象创建实例
JSONObject item1 = new JSONObject();
item1.put("name", "张三");
item1.put("age", 25);
JSONObject item2 = new JSONObject();
item2.put("name", "李四");
item2.put("age", 30);
// 创建JSONArray并将JSONObject实例添加进去
JSONArray jsonArray = new JSONArray();
jsonArray.add(item1);
jsonArray.add(item2);
// 将JSONArray添加到外部JSONObject的特定key下
outerJsonObject.put("users", jsonArray);
// 将外部的JSONObject转换为JSON字符串
String jsonString = outerJsonObject.toString();
// 打印JSON字符串
System.out.println(jsonString);
}
}