Json 是目前互联网应用使用最为广泛的信息交换格式之一。Spring Boot 内置了 Jackson。spring Boot 默认采用了 Jackson来处理诸如 @RequestBody @ResponseBody
1.测试类
@Setter
@Getter
public class User{
@NonNull
private Long id;
private String username;
@JsonIgnore // 此注解用于属性上,作用是进行JSON操作时忽略该属性
private String password;
@JsonProperty("date") // 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // 此注解用于属性上,作用是把Date类型直接转化为想要的格式,如@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")。
private Date createTime;
}
2.转换类ObjectMapper
在jackson中主要用于json转换的主要是ObjectMapper 类。
ObjectMapper mapper = new ObjectMapper();
3.测试
3.1 对象转json
User user = new User();
user.setId(11L);
user.setPassword("123456");
user.setUsername("yong");
user.setCreateTime(new Date());
ObjectMapper mapper = new ObjectMapper();
String s = mapper.writeValueAsString(user);
System.out.println(s);
结果:
3.2 map转json
Map<String,Object> map = new HashMap<>();
map.put("id",12);
map.put("name","wanyong");
map.put("sex","man");
map.put("createTime",new Date());
String s = mapper.writeValueAsString(map);
System.out.println(s);
3.3 json转map(对象)
String str = "{\"id\":11,\"username\":\"yong\",\"nickName\":\"wanyong\",\"sex\":\"man\"}";
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(str, Map.class); // 转成对象,可以写成User.class
System.out.println(map.get("id").toString());
配置 Jackson
默认采用了 Jackson ,但返回的日期格式没有展示人们常用的格式,就要我们从 applicaiton中配置他的展示格式。
server.port = 8086
#jackson
#日期格式化
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#spring.jackson.date-format=yyyy-MM-dd
#格式化输出
spring.jackson.serialization.indent_output=true
#忽略无法转换的对象
spring.jackson.serialization.fail_on_empty_beans=false
#设置空如何序列化
spring.jackson.defaultPropertyInclusion=NON_EMPTY
#允许对象忽略json中不存在的属性
spring.jackson.deserialization.fail_on_unknown_properties=false
#允许出现特殊字符和转义符
spring.jackson.parser.allow_unquoted_control_chars=true
#允许出现单引号
spring.jackson.parser.allow_single_quotes=true
参考
http://www.manongjc.com/detail/10-zmjxmzwqxfqqeud.html
版权声明:本文为qq_35500925原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。