Fetch the repository succeeded.
package org.example.hutool.utilTest.json;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.*;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.time.DateUtils;
import org.junit.Test;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.*;
/**
* JSON 使用教程
*
* @author wangMaoXiong
* @version 1.0
* @date 2022/12/1 19:35
*/
@SuppressWarnings("all")
public class JsonTest {
/**
* JSONUtil.createObj()是快捷新建JSONObject的工具方法,同样我们可以直接 new;
*/
@Test
public void createObjTest1() throws ParseException {
JSONObject json1 = JSONUtil.createObj()
.set("a", "value1")
.set("b", "value2")
.set("c", "value3");
// {"a":"value1","b":"value2","c"""value3"}
System.out.println(json1);
Map<String, Object> map = new LinkedHashMap<>();
map.put("key1", "One");
map.put("key2", "Two");
map.put("level", 1);
map.put("is_marry", false);
map.put("is_leaf", 0);
map.put("birthday", DateUtils.parseDate("1993-08-25 12:15:00", "yyyy-MM-dd HH:mm:ss"));
JSONObject json2 = new JSONObject();
json2.putAll(map);
// Wed Aug 25 12:15:00 CST 1993
System.out.println(json2.getDate("birthday"));
// {"key1":"One","birthday":746252100000,"key2":"Two","is_marry":false,"level":1,"is_leaf":0}
System.out.println(json2.toStringPretty());
}
/**
* 创建 JSONArray
*/
@Test
public void createArrayTest1() {
//方法1
JSONArray array1 = JSONUtil.createArray();
//方法2
JSONArray array2 = new JSONArray();
array1.add("value1");
array1.add("value2");
array2.add("value3");
array2.add("value4");
array2.add("value5");
// ["value1","value2"]
System.out.println(array1);
/**
* [
* "value3",
* "value4",
* "value5"
* ]
*/
System.out.println(JSONUtil.toJsonPrettyStr(array2));
}
/**
* JSONUtil.toJsonStr 可以将任意对象(Bean、Map、集合等)直接转换为JSON字符串。
* String toJsonPrettyStr(Object obj) :转换为格式化后的JSON字符串
* * 1、如果对象是有序的Map等对象,则转换后的JSON字符串也是有序的。
* * 2、JSON对象转字符串(一行) jsonObject.toString();
* * 3、也可以美化一下,即显示出带缩进的JSON: jsonObject.toStringPretty();
* * 4、日期默认序列化为 Long 类型. 此时需要使用 JSONConfig。
* * 5、值为 null 的属性默认不会转换.
* String toJsonStr(Object obj, JSONConfig jsonConfig) - 转换为JSON字符串
* * @param obj 被转为JSON的对象
* * @param jsonConfig JSON配置
* * @since 5.7.12
*/
@Test
public void testToJsonStr1() throws ParseException {
Map<String, Object> map = new LinkedHashMap<>();
map.put("key1", "One");
map.put("key2", new ArrayList<>());
map.put("userList", Lists.newArrayList("张三", "李四"));
map.put("level", 1);
map.put("sal", -500.56);
map.put("is_marry", false);
map.put("is_leaf", null); // 默认 null 值不会转换
map.put("birthday", DateUtils.parseDate("1993-08-25 12:15:00", "yyyy-MM-dd HH:mm:ss"));
map.put("birthday2", DateUtils.parseDate("1993-08-25 12:15:00", "yyyy-MM-dd HH:mm:ss"));
// {"key1":"One","key2":[],"userList":["张三","李四"],"level":1,"sal":-500.56,"is_marry":false,"birthday":746252100000,"birthday2":746252100000}
System.out.println(JSONUtil.toJsonStr(map));
// {"key1":"One","key2":[],"userList":["张三","李四"],"level":1,"sal":-500.56,"is_marry":false,"birthday":746252100000,"birthday2":746252100000}
String prettyStr = JSONUtil.toJsonPrettyStr(map);
System.out.println(prettyStr);
// {"key1":"One","key2":[],"userList":["张三","李四"],"level":1,"sal":-500.56,"is_marry":false,"is_leaf":null,"birthday":"1993-08-25 12:15:00","birthday2":"1993-08-25 12:15:00"}
JSONConfig jsonConfig = JSONConfig.create();
jsonConfig.setIgnoreNullValue(false);
jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
String jsonStr = JSONUtil.toJsonStr(map, jsonConfig);
System.out.println(jsonStr);
}
/**
* JSON 字符串解析
*/
@Test
public void parseObjTest1() {
String jsonStr = "{\"key1\":\"One\",\"birthday\":746252100000,\"key2\":\"Two\",\"is_marry\":false,\"level\":1,\"is_leaf\":0}";
//方法一:使用工具类转换
JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
//方法二:new的方式转换
JSONObject jsonObject2 = new JSONObject(jsonStr);
// {"key1":"One","birthday":746252100000,"key2":"Two","is_marry":false,"level":1,"is_leaf"")}
System.out.println(jsonObject);
// {"key1":"One","birthday":746252100000,"key2":"Two","is_marry":false,"level":1,"is_leaf":0}
System.out.println(jsonObject2);
}
/**
* 默认的,Hutool将日期输出为时间戳,如果需要自定义日期格式,可以调用 json.setDateFormat("yyyy-MM-dd HH:mm:ss");
*
* @throws ParseException
*/
@Test
public void parseObjTest2() throws ParseException {
Map<String, Object> map = new LinkedHashMap<>();
map.put("key1", "One");
map.put("key2", "Two");
map.put("level", 1);
map.put("is_marry", false);
map.put("is_leaf", 0);
map.put("birthday", DateUtils.parseDate("1993-08-25 12:15:00", "yyyy-MM-dd HH:mm:ss"));
JSONObject jsonObject = JSONUtil.parseObj(map);
jsonObject.setDateFormat("yyyy-MM-dd HH:mm:ss");
// {
// "key1": "One",
// "key2": "Two",
// "level": 1,
// "is_marry": false,
// "is_leaf": 0,
// "birthday": "1993-08-25 12:15:00"
// }
System.out.println(jsonObject.toStringPretty());
}
/**
* JSONObject parseObj(Object obj, boolean ignoreNullValue, boolean isOrder)
* * @param obj Bean对象或者Map
* * @param ignoreNullValue 是否忽略空值,默认不忽略;
* * @param isOrder 输出的字段顺序是否和Bean的字段顺序一致,默认不一致;
*
* @throws ParseException
*/
@Test
public void parseObjTest3() throws ParseException {
Map<String, List<Person>> personMap = new LinkedHashMap<>();
Person person1 = new Person(1, "张三", DateUtils.parseDate("1993-03-21 10:15:00", "yyyy-MM-dd HH:mm:ss"), 5000F);
Person person2 = new Person(2, "李四", DateUtils.parseDate("1994-04-22 11:15:00", "yyyy-MM-dd HH:mm:ss"), 6000F);
Person person3 = new Person(3, "王五", DateUtils.parseDate("1995-05-23 12:15:00", "yyyy-MM-dd HH:mm:ss"), 7000F);
Person person4 = new Person(4, "马六", DateUtils.parseDate("1996-06-24 13:15:00", "yyyy-MM-dd HH:mm:ss"), 11180.88F);
Person person5 = new Person(5, "赵七", DateUtils.parseDate("1997-07-25 14:15:00", "yyyy-MM-dd HH:mm:ss"), 11190.00F);
List<Person> class1 = new ArrayList<>();
List<Person> class2 = new ArrayList<>();
List<Person> class3 = new ArrayList<>();
class1.add(person1);
class2.add(person2);
class2.add(person3);
class3.add(person4);
class3.add(person5);
personMap.put("class1", class1);
personMap.put("class2", class2);
personMap.put("class3", class3);
// [{"id":4,"name":"马六","birthday":835593300000,"salary":11180.88},{"id":5,"name":"赵七","birthday":869811300000,"salary":11190}]
String class3JsonStr = JSONUtil.toJsonPrettyStr(class3);
System.out.println(class3JsonStr);
System.out.println("=======================");
// {
// "class1":[{"id":1,"name":"张三","age":null,"birthday":732680100000,"salary":5000}],
// "class2":[{"id":2,"name":"李四","age":null,"birthday":766984500000,"salary":6000},
// {"id":3,"name":"王五","age":null,"birthday":801202500000,"salary":7000}],
// "class3":[{"id":4,"name":"马六","age":null,"birthday":835593300000,"salary":11180.88},
// {"id":5,"name":"赵七","age":null,"birthday":869811300000,"salary":11190}]
// }
JSONObject json = JSONUtil.parseObj(personMap, false, true);
Console.log(json.toStringPretty());
System.out.println("=======================");
// {
// "class1":[{"id":1,"name":"张三","age":null,"birthday":"1993-03-21 10:15:00","salary":5000}],
// "class2":[{"id":2,"name":"李四","age":null,"birthday":"1994-04-22 11:15:00","salary":6000},
// {"id":3,"name":"王五","age":null,"birthday":"1995-05-23 12:15:00","salary":7000}],
// "class3":[{"id":4,"name":"马六","age":null,"birthday":"1996-06-24 13:15:00","salary":11180.88},
// {"id":5,"name":"赵七","age":null,"birthday":"1997-07-25 14:15:00","salary":11190}]
// }
JSONConfig jsonConfig = JSONConfig.create();
jsonConfig.setIgnoreNullValue(false);
jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
JSONObject jsonObject = JSONUtil.parseObj(personMap, jsonConfig);
System.out.println(jsonObject);
}
/**
* String toXmlStr(JSON json)
* 转换为XML字符串
* <p>
* JSONObject xmlToJson(String xml)
* * XML 转 JSONObject<br>
* * 转换过程中一些信息可能会丢失,JSON中无法区分节点和属性,相同的节点将被处理为JSONArray。
*
* @param json JSON
* @return XML字符串
*/
@Test
public void toXmlStrTest1() {
String jsonStr = "{\"class3\":[{\"birthday\":746165700000,\"salary\":5000,\"name\":\"张三\",\"id\":1,\"age\":null},{\"birthday\":746252100000,\"salary\":5000,\"name\":\"张三\",\"id\":1,\"age\":null}],\"class2\":[{\"birthday\":745992900000,\"salary\":5000,\"name\":\"张三\",\"id\":1,\"age\":null},{\"birthday\":746079300000,\"salary\":5000,\"name\":\"张三\",\"id\":1,\"age\":null}],\"class1\":[{\"birthday\":745906500000,\"salary\":5000,\"name\":\"张三\",\"id\":1,\"age\":null}]}";
JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
String xmlStr = JSONUtil.toXmlStr(jsonObject);
// <class3><birthday>746165700000</birthday><salary>5000</salary><name>张三</name><id>1</id><age>null</age></class3><class3><birthday>746252100000</birthday><salary>5000</salary><name>张三</name><id>1</id><age>null</age></class3><class2><birthday>745992900000</birthday><salary>5000</salary><name>张三</name><id>1</id><age>null</age></class2><class2><birthday>746079300000</birthday><salary>5000</salary><name>张三</name><id>1</id><age>null</age></class2><class1><birthday>745906500000</birthday><salary>5000</salary><name>张三</name><id>1</id><age>null</age></class1>
System.out.println(xmlStr);
JSONObject xmlToJson = JSONUtil.xmlToJson(xmlStr);
System.out.println();
// {"class3":[{"birthday":746165700000,"salary":5000,"name":"张三","id":1,"age":""},{"birthday":746252100000,"salary":5000,"name":"张三","id":1,"age":""}],"class2":[{"birthday":745992900000,"salary":5000,"name":"张三","id":1,"age":""},{"birthday":746079300000,"salary":5000,"name":"张三","id":1,"age":""}],"class1":{"birthday":745906500000,"salary":5000,"name":"张三","id":1,"age":""}}
System.out.println(JSONUtil.toJsonStr(xmlToJson));
}
/**
* JSONArray parseArray(String jsonStr)
* * JSON 字符串转 JSONArray
*/
@Test
public void parseArrayTest1() {
String jsonStr = "[{\"birthday\":746165700000,\"salary\":5000,\"name\":\"张三\",\"id\":1},{\"birthday\":746252100000,\"salary\":5000,\"name\":\"张三\",\"id\":1}]";
JSONArray jsonArray = JSONUtil.parseArray(jsonStr);
// [{"birthday":746165700000,"salary":5000,"name":"张三","id":1},{"birthday":746252100000,"salary":5000,"name":"张三","id":1}]
System.out.println(jsonArray);
List<Person> personList = JSONUtil.toList(jsonArray, Person.class);
System.out.println(personList);
}
/**
* List<T> toList(JSONArray jsonArray, Class<T> elementType)
* List<T> toList(String jsonArray, Class<T> elementType)
* 将JSONArray字符串转换为Bean的List,默认为ArrayList
* * @param jsonArray JSONArray字符串
* * @param elementType List中元素类型
*/
@Test
public void toListTest1() {
String jsonStr = "[{\"birthday\":746165700000,\"salary\":5000,\"name\":\"张三\",\"id\":1},{\"birthday\":746252100000,\"salary\":5000,\"name\":\"张三\",\"id\":1}]";
List<Person> personList = JSONUtil.toList(jsonStr, Person.class);
// [Person{id=1, name='张三', age=null, birthday=Tue Aug 24 12:15:00 CST 1993, salary=5000.0}, Person{id=1, name='张三', age=null, birthday=Wed Aug 25 12:15:00 CST 1993, salary=5000.0}}
System.out.println(personList);
}
/**
* 转换为数组
*/
@Test
public void toArrayTest1() {
String jsonStr = "[{\"birthday\":746165700000,\"salary\":5000,\"name\":\"张三\",\"id\":1},{\"birthday\":746252100000,\"salary\":5000,\"name\":\"张三\",\"id\":1}]";
JSONArray jsonArray = JSONUtil.parseArray(jsonStr);
Person[] toArray = jsonArray.toArray(new Person[0]);
// [Person{id=1, name='张三', age=null, birthday=Tue Aug 24 12:15:00 CST 1993, salary=5000.0}, Person{id=1, name='张三', age=null, birthday=Wed Aug 25 12:15:00 CST 1993, salary=5000.0}]
Console.log(toArray);
}
/**
* T toBean(String jsonString, Type beanType, boolean ignoreError)
* JSON字符串转为实体类对象,转换异常将被抛出
* * @param <T> Bean类型
* * @param jsonString JSON字符串
* * @param beanType 实体类对象类型
* * @param ignoreError 是否忽略错误
*/
@Test
public void toBeanTest1() {
String jsonStr = "[{\"birthday\":746165700000,\"salary\":5000,\"name\":\"张三\",\"id\":1},{\"birthday\":746252100000,\"salary\":5000,\"name\":\"张三\",\"id\":1}]";
List<Person> personList = JSONUtil.toBean(jsonStr, new TypeReference<List<Person>>() {
}.getType(), true);
// [Person{id=1, name='张三', age=null, birthday=Tue Aug 24 12:15:00 CST 1993, salary=5000.0}, Person{id=1, name='张三', age=null, birthday=Wed Aug 25 12:15:00 CST 1993, salary=5000.0}}
System.out.println(personList);
}
/**
* T toBean(String jsonString, TypeReference<T> typeReference, boolean ignoreError)
* * JSON字符串转为实体类对象,转换异常将被抛出
* * @param <T> Bean类型
* * @param jsonString JSON字符串
* * @param typeReference {@link TypeReference}类型参考子类,可以获取其泛型参数中的Type类型
* * @param ignoreError 是否忽略错误
*/
@Test
public void toBeanTest2() {
String jsonStr = "{\"class3\":[{\"birthday\":746165700000,\"salary\":5000,\"name\":\"张三\",\"id\":1,\"age\":\"\"}," +
"{\"birthday\":\"2003-08-25 12:50:41\",\"salary\":5000,\"name\":\"李四光\",\"id\":1,\"age\":\"\"}],\"class2\":[{\"birthday\":745992900000,\"salary\":5000,\"name\":\"张三\",\"id\":1,\"age\":\"\"},{\"birthday\":746079300000,\"salary\":5000,\"name\":\"张三\",\"id\":1,\"age\":\"\"}],\"class1\":{\"birthday\":745906500000,\"salary\":5000,\"name\":\"张三\",\"id\":1,\"age\":\"\"}}";
Map<String, List<Person>> personMap = JSONUtil.toBean(jsonStr, new TypeReference<Map<String, List<Person>>>() {
}, true);
// {class3=[Person{id=1, name='张三', age=null, birthday=Tue Aug 24 12:15:00 CST 1993, salary=5000.0},
// Person{id=1, name='李四光', age=null, birthday=Mon Aug 25 12:50:41 CST 2003, salary=5000.0}],
// class2=[Person{id=1, name='张三', age=null, birthday=Sun Aug 22 12:15:00 CST 1993, salary=5000.0},
// Person{id=1, name='张三', age=null, birthday=Mon Aug 23 12:15:00 CST 1993, salary=5000.0}],
// class1=[Person{id=1, name='张三', age=null, birthday=Sat Aug 21 12:15:00 CST 1993, salary=5000.0}]}
System.out.println(personMap);
}
/**
* Object getByPath(String expression)
* Object getByPath(JSON json, String expression)
* 如果JSON的层级特别深,那么获取某个值就变得非常麻烦,代码也很臃肿,Hutool提供了getByPath方法可以通过表达式获取JSON中的值。
* * <ol>
* * <li>.表达式,可以获取Bean对象中的属性(字段)值或者Map中key对应的值</li>
* * <li>[]表达式,可以获取集合等对象中对应index的值</li>
* * </ol>
* * <p>
* * 表达式栗子:
* * <pre>
* * persion
* * persion.name
* * persons[3]
* * person.friends[5].name
* * </pre>
*/
@Test
public void getByPathTest1() {
String jsonStr = "[{\"birthday\":746165700000,\"salary\":5000,\"name\":\"张三\",\"id\":1},{\"birthday\":746252100000,\"salary\":5000,\"name\":\"张三\",\"id\":1}]";
JSONArray jsonArray = JSONUtil.parseArray(jsonStr);
/**
* [
* {
* "birthday": 746165700000,
* "salary": 5000,
* "name": "张三",
* "id": 1
* },
* {
* "birthday": 746252100000,
* "salary": 5000,
* "name": "张三",
* "id": 1
* }
* ]
*/
System.out.println(JSONUtil.toJsonPrettyStr(jsonArray));
Date birthday = jsonArray.getByPath("[0].birthday", Date.class);
Object salary = JSONUtil.getByPath(jsonArray, "[1].salary");
Object name = jsonArray.getByPath("[2].name");
// Tue Aug 24 12:15:00 CST 1993
System.out.println(birthday);
// 5000
System.out.println(salary);
// null
System.out.println(name);
}
/**
* boolean isNull(Object obj): 是否为null对象,null的情况包括:
* <pre>
* 1. {@code null}
* 2. {@link JSONNull}
* </pre>
*/
@Test
public void testIsNull() {
/**
* 特别注意:
* 特别注意:
* 特别注意:
* 从字符串反序列化对为对象,其中的 null 值会变成 cn.hutool.json.JSONNull 类型,
* 导致后续如果需要判断是否为null,普通的的方式全部失效了,必须使用它的方法进行判断。
* 此时推荐使用 Map map = com.alibaba.fastjson.JSONObject.parseObject(content, Map.class);
*/
String text = "{\"biz_key\":\"null\",\"update_time\":\"2024-01-11 15:42:42\",\"pos_code\":\"\",\"image_list\":[],\"affix_list\":null}";
Map<String, Object> map = JSONUtil.toBean(text, Map.class);
// {biz_key=null, update_time=2024-01-11 15:42:42, pos_code=, image_list=[], affix_list=null}
System.out.println(map);
// null,class java.lang.String,true
System.out.println(map.get("biz_key") + "," + map.get("biz_key").getClass() + "," + "null".equals(map.get("biz_key").toString()));
// ,class java.lang.String,true
System.out.println(map.get("pos_code") + "," + map.get("pos_code").getClass() + "," + ObjectUtil.isEmpty(map.get("pos_code")));
// [],class cn.hutool.json.JSONArray,true
System.out.println(map.get("image_list") + "," + map.get("image_list").getClass() + "," + ObjectUtil.isEmpty(map.get("image_list")));
// null,class cn.hutool.json.JSONNull
System.out.println(map.get("affix_list") + "," + map.get("affix_list").getClass());
// false
System.out.println(ObjectUtil.isEmpty(map.get("affix_list")));
// false
System.out.println(map.get("affix_list") == null);
// true
System.out.println(JSONUtil.isNull(map.get("affix_list")));
// false
System.out.println(JSONUtil.isNull(map.get("pos_code")));
// false
System.out.println(JSONUtil.isNull(map.get("image_list")));
}
/**
* 转换对象为指定的对象类型,比如经常会遇到,需要将某个内容转为需要的对象类型。
* 比如 String 转 Java Bean、Map、List 等等。
* 也可以反过来对象转字符串。
*
* @param obj :源对象。比如:String、Array、Iterable、Iterator、Java Bean对象。
* @param typeReference :目标对象类型,比如 Java Bean、Map、List、String 等等。
* @return 返回目标对象
*/
public static <T> T objToTargetType(Object resource, Type targetType) {
if (ObjUtil.isEmpty(resource)) {
return null;
}
JSONConfig jsonConfig = JSONConfig.create();
jsonConfig.setIgnoreNullValue(false);
jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
JSON parse = JSONUtil.parse(resource, jsonConfig);
return JSONUtil.toBean(parse, targetType, false);
}
@Test
public void testObjToTargetType() {
String jsonArrStr = "[{\"id\":4,\"name\":\"马六\",\"birthday\":835593300000,\"salary\":11180.88},{\"id\":5,\"name\":\"赵七\",\"birthday\":869811300000,\"salary\":11190}]";
List<Person> personList = JsonTest.objToTargetType(jsonArrStr, new TypeReference<List<Person>>() {
});
// [Person{id=4, name='马六', age=null, birthday=Mon Jun 24 13:15:00 CST 1996, salary=11180.88}, Person{id=5, name='赵七', age=null, birthday=Fri Jul 25 14:15:00 CST 1997, salary=11190.0}]
System.out.println(personList);
System.out.println("======================");
String personJsonStr = JsonTest.objToTargetType(personList, new TypeReference<String>() {
});
// [{"id":4,"name":"马六","age":null,"birthday":"1996-06-24 13:15:00","salary":11180.88},{"id":5,"name":"赵七","age":null,"birthday":"1997-07-25 14:15:00","salary":11190}]
System.out.println(personJsonStr);
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。