application.properties中配置
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
实体类
@Data
@Builder
public class Model {
private Integer id;
private int age;
private String name;
private Date createTime;
}
测试controller
@GetMapping("/jackson/type1/res")
public Model res() {
return Model.builder().id(1).age(12).name("zhangsan").createTime(new Date()).build();
}
测试结果
实体
@Data
@Builder
public class Model {
private Integer id;
private int age;
private String name;
@JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss")
private Date createTime;
}
测试controller
@GetMapping("/jackson/type1/res2")
public Model res2() {
return Model.builder().id(1).age(12).name("zhangsan").createTime(new Date()).build();
}
测试结果
实体
@Data
@Builder
@JsonPropertyOrder(value={"name", "age"})
public class Model {
private Integer id;
private int age;
private String name;
@JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss")
private Date createTime;
}
测试结果
实体类
@Data
@Builder
@JsonPropertyOrder(value={"name", "age"})
public class Model {
private Integer id;
private int age;
@JsonProperty("myName")
private String name;
@JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss")
private Date createTime;
}
测试结果
实体类
@Data
@Builder
@JsonPropertyOrder(value={"name", "age"})
public class Model {
@JsonInclude(value= JsonInclude.Include.NON_NULL)
private Integer id;
private int age;
@JsonProperty("myName")
private String name;
@JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss")
private Date createTime;
}
测试controller
@GetMapping("/jackson/type1/res3")
public Model res3() {
return Model.builder().age(12).name("zhangsan").createTime(new Date()).build();
}
测试结果
实体类
@Data
@Builder
@JsonPropertyOrder(value={"name", "age"})
public class Model {
@JsonInclude(value= JsonInclude.Include.NON_NULL)
private Integer id;
@JsonIgnore
private int age;
@JsonProperty("myName")
private String name;
@JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss")
private Date createTime;
}
测试结果
1.获取ObjectMapper对象:jackjson使用ObjectMapper对象进行对象和json格式数据的转换
public ObjectMapper mapper = new ObjectMapper();
2.json格式字符串转化为java对象
mapper.readValue(json, tClass);//第一个参数为json格式的字符串,第二个参数为转换的java对象.class
3.json格式字符串转换为LIst
mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, eClass));
//json是json格式字符串,eClass参数是LIst集合中的元素类.class
4.json格式字符中转换为Map
mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, kClass, vClass));
5.java对象转为json格式字符串
mapper.writeValueAsString(obj);
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_43296313/article/details/125100339
内容来源于网络,如有侵权,请联系作者删除!