Java操作json的库
库很多,这里以fastjson为例
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
Hutool 一个小而全的工具库
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.4</version>
</dependency>
java操作json 实操
序列化
package com.sheep.emo.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Description : Person实体类
* @Author : sheep669
* @Created at 2022/7/8 22:13
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private Integer userId;
private String userName;
private String pwd;
private String location;
private Character sex;
}
package com.sheep.emo;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.sheep.emo.pojo.Person;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class EmoApplicationTests {
@Test
void contextLoads() {
Person person = new Person();
person.setUserId(12);
person.setUserName("张三");
person.setSex('男');
person.setPwd("23242");
person.setLocation("北京市公安局");
String s = JSON.toJSONString(person);
System.out.println(s);
// StrUtil.toUnderlineCase(s) 驼峰转下划线
String s1 = StrUtil.toUnderlineCase(s);
System.out.println(s1);
}
}
{"location":"北京市公安局","pwd":"23242","sex":"男","userId":12,"userName":"张三"}
{"location":"北京市公安局","pwd":"23242","sex":"男","user_id":12,"user_name":"张三"}
Process finished with exit code 0
允许字段为空
// SerializerFeature.WriteMapNullValue 允许字段为空
String s = JSON.toJSONString(person, SerializerFeature.WriteMapNullValue);
System.out.println(s);
console
{"location":"北京市公安局","pwd":"23242","sex":"男","userId":12,"userName":null}
处理时间格式
// 实体类加上注解
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime birthday;
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
原来:
{"birthday":"2022-07-08T22:59:16.604","createTime":1657292356604}
{"birthday":"2022-07-08T22:59:16.604","create_time":1657292356604}
现在:
{"birthday":"2022-07-08 23:00:24","createTime":"2022-07-08 23:00:24"}
{"birthday":"2022-07-08 23:00:24","create_time":"2022-07-08 23:00:24"}
集合序列化后面出现 $ref 引用探测
@Test
public void test$Ref() {
List<Person> list = new ArrayList<>();
Person person = new Person();
person.setUserName("张三");
person.setPwd("23242");
person.setLocation("北京市公安局");
list.add(person);
list.add(person);
list.add(person);
String s = JSON.toJSONString(list);
System.out.println(s);
}
console
[{"location":"北京市公安局","pwd":"23242","userName":"张三"},{"$ref":"$[0]"},{"$ref":"$[0]"}]
// SerializerFeature.DisableCircularReferenceDetect 禁用引用探测功能
String s = JSON.toJSONString(list, SerializerFeature.DisableCircularReferenceDetect);
System.out.println(s);
console
[{"location":"北京市公安局","pwd":"23242","userName":"张三"},{"location":"北京市公安局","pwd":"23242","userName":"张三"},{"location":"北京市公安局","pwd":"23242","userName":"张三"}]
序列化定制处理 以key转大写为例
@Test
public void testSerializeFilter() {
Person person = new Person();
person.setUserId(1);
person.setUserName("张三");
person.setSex('男');
person.setLocation("北京市公安局");
//指定输出json的key大写
//Object var1:对象 String var2:属性 Object var3:值
NameFilter nameFilter = (object, key, value) -> {
// 进行处理
return key.toUpperCase();
};
String s = JSON.toJSONString(person, nameFilter);
System.out.println(s);
}
console
{"LOCATION":"北京市公安局","SEX":"男","USERID":1,"USERNAME":"张三"}
命名补全,自定义
@JSONField(name = "xxxx")
原来:
{"pwd":"23242"}
@JSONField(name = "password")
private String pwd;
现在:
{"password":"23242"}
美化输出
一般不用
@Test
void contextLoads() {
Person person = new Person();
person.setUserId(12);
// person.setUserName("张三");
person.setSex('男');
person.setPwd("23242");
person.setLocation("北京市公安局");
person.setBirthday(LocalDateTime.now());
person.setCreateTime(new Date());
// SerializerFeature.WriteMapNullValue 允许字段为空 SerializerFeature.PrettyFormat 美化输出
String s = JSON.toJSONString(person, SerializerFeature.WriteMapNullValue, SerializerFeature.PrettyFormat);
System.out.println(s);
String s1 = StrUtil.toUnderlineCase(s);
System.out.println(s1);
}
console
{
"birthday":"2022-07-09 00:04:11",
"createTime":"2022-07-09 00:04:11",
"location":"北京市公安局",
"pwd":"23242",
"sex":"男",
"userId":12,
"userName":null
}
{
"birthday":"2022-07-09 00:04:11",
"create_time":"2022-07-09 00:04:11",
"location":"北京市公安局",
"pwd":"23242",
"sex":"男",
"user_id":12,
"user_name":null
}
java操作json 实操
反序列化
@Test
public void test() {
String jsonString = "{\"birthday\":\"2022-07-08 23:30:29\",\"create_time\":\"2022-07-08 23:30:29\",\"location\":\"北京市公安局\",\"pwd\":\"23242\",\"sex\":\"男\",\"user_id\":12,\"user_name\":null}";
//反序列化 JSON.parseObject()
Person person = JSON.parseObject(jsonString, Person.class);
System.out.println(person);
}
console
Person(userId=12, userName=null, pwd=23242, location=北京市公安局, sex=男, birthday=2022-07-08T23:30:29, createTime=Fri Jul 08 23:30:29 CST 2022)
package com.sheep.emo.pojo;
import lombok.Data;
/**
* @Description : TODO
* @Author : sheep669
* @Created at 2022/7/8 23:35
*/
@Data
public class ResultVO<T> {
private Boolean success;
private T data;
private ResultVO() {
}
public static <T> ResultVO<T> buildSuccess(T t) {
ResultVO<T> resultVO = new ResultVO<>();
resultVO.setData(t);
return resultVO;
}
}
@Test
public void test() {
String jsonString2 = "{\"data\":{\"birthday\":\"2022-07-08 23:30:29\",\"createTime\":\"2022-07-08 23:30:29\",\"location\":\"北京市公安局\",\"pwd\":\"23242\",\"sex\":\"男\",\"userId\":12}}";
// 反序列化不能获取到泛型 需要强制类型转换
ResultVO resultVO = JSON.parseObject(jsonString2, ResultVO.class);
Object data1 = resultVO.getData();
Person person1 =(Person) resultVO.getData();
System.out.println(person1.getUserName());
System.out.println((Person)data1);
// new TypeReference<ResultVO<Person>>() {} 需要什么类型传什么,这里是ResultVO<Person>
ResultVO<Person> personResultVO1 = JSON.parseObject(jsonString2, new TypeReference<ResultVO<Person>>() {});
// 直接就拿到了Person对象
Person person2 = personResultVO1.getData();
System.out.println(person2.getUserName());
}
指定某个字段不参与序列化
@JSONField(serialize = false, deserialize = false)
// 不参与序列化和反序列化 serialize = false, deserialize = false
@JSONField(serialize = false, deserialize = false)
private String pwd;