1、创建JSONObject
JSONObject jsonObject = JSONUtil.createObj() .put("姓名","张三") .put("年龄",12) .put("国籍","中国") .put("爱好","徒步"); System.out.println(jsonObject); //{"姓名":"张三","爱好":"徒步","国籍":"中国","年龄":12} JSONObject object = new JSONObject(); object.append("姓名","张三") .append("年龄",12) .append("国籍","中国") .append("爱好","徒步"); System.out.println(object.toString()); //{"姓名":["张三"],"爱好":["徒步"],"国籍":["中国"],"年龄":[12]}
2、解析JSONObject
//解析json字符串 //方式1 String jsonStr = "{"b":"value2","c":"value3","a":"value1"}"; JSONObject jsonObject2 = JSONUtil.parseObj(jsonStr); System.out.println(jsonObject2); //{"a":"value1","b":"value2","c":"value3"} //方式2 JSONObject object3 = new JSONObject(jsonStr); System.out.println(object3); //{"a":"value1","b":"value2","c":"value3"}
3、JavaBean解析
@Data public class UserA { private String name; private String a; private Date date; private List<Seq> sqs; }
UserA userA = new UserA(); userA.setName("nameTest"); userA.setDate(new Date()); userA.setSqs(CollectionUtil.newArrayList(new Seq(null), new Seq("seq2"))); JSONObject json = JSONUtil.parseObj(userA,false,true); System.out.println(json.toStringPretty()); //{ // "name": "nameTest", // "a": null, // "date": 1631158148011, // "sqs": [ // { // }, // { // } // ] //}
4、JSON数组-JSONArray
//jsonArray的解析 //方式1 JSONArray array = JSONUtil.createArray(); array.add("11"); array.add("22"); array.add("33"); System.out.println(array.toString()); //["11","22","33"] //方式2 JSONArray array1 = new JSONArray(); array1.add("11"); array1.add("22"); array1.add("33"); System.out.println(array1.toString()); //["11","22","33"] //解析json数组 String jsonStr4 = "["value1", "value2", "value3"]"; JSONArray array3 = JSONUtil.parseArray(jsonStr4); System.out.println(array3); //["value1","value2","value3"]