标签:ping package .class ignore spring setname desc led port
接下来我们在看一段代码,这段代码是常用注解在实体类User中的简单使用:
package zone.reborn.springbootstudy.entity;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
/**
* @author 作者: reborn
* @version 创建时间: 2018年7月15日 下午3:59:45
* @description 类说明:用户实体类
*/
public class User {
private String name;
@JsonIgnore // 利用底层jackson注解
private String password;
private Integer age;
@JsonFormat(pattern = "yy-MM-dd HH:mm:ss a", locale = "zh", timezone = "GMT+8")//yy-MM-dd HH:mm:ss
private Date birthday;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
单独拿出来,聊聊:
@JsonIgnore 忽略此属性,比如password我并不想返回给前端,就可以添加此注解
@JsonFormat(pattern = "yy-MM-dd HH:mm:ss a", locale = "zh", timezone = "GMT+8") 进行数据格式化
@JsonInclude(JsonInclude.Include.NON_NULL) 如果此字段为null不返回该字段数据。
@JsonProperty(value = "user_name") 指定序列化时的字段名,默认使用属性名
@JsonUnwrapped(prefix = "user_")
把成员对象中的属性提升到其容器类,并添加给定的前缀,比如上例中: User类中有name和age两个属性,不使用此注解则序列化为:
... "user": { "name": "xxx", "age": 22 } ...
使用此注解则序列化为:
... "user_name": "xxx", "user_age": 22, ..
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id") 作用于类或属性上,被用来在序列化/反序列化时为该对象或字段添加一个对象识别码,通常是用来解决循环嵌套的问
@PostMapping("/jackson")
@ResponseBody
public Object jackson() {
User user = new User();
user.setName("小明");
user.setEmail("xiaoming@qq.com");
user.setAge(20);
ObjectMapper objectMapper = new ObjectMapper();
// 将对象转换成json格式 格式化时间类型数据
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//对象转json
String json = objectMapper.writeValueAsString(user);
System.out.println(json);
// 将json格式转换成对象
User user2 = objectMapper.readValue(json, User.class);
System.out.println(user2.toString());
// 将集合转换成json
List<User> list = new ArrayList<User>();
list.add(user);
String jsonString = objectMapper.writeValueAsString(list);
System.out.println(jsonString);
// json转换成集成对象
objectMapper.writeValue(new File("E:/lib/jackjson/jackjsonTest.txt"), jsonString);
User user3 = new Lisi();
user3.setAge(30);
user3.setBirthday(new Date());
user3.setEmail("11@22.com");
user3.setName("lisi");
System.out.println(objectMapper.writeValueAsString(user3));
}
标签:ping package .class ignore spring setname desc led port
原文地址:https://www.cnblogs.com/xiaowangbangzhu/p/10302068.html