springboot复习三—(jackson)
1.jackson常用注解https://github.com/FasterXML/jackson-annotations@JsonInclude@JsonIgnor@JsonFormat@JsonProperty@JsonInclude(JsonInclude.Include.NON_NULL)//username为空时不返回private String username;...
·
1.jackson常用注解
https://github.com/FasterXML/jackson-annotations
@JsonInclude
@JsonIgnor
@JsonFormat
@JsonProperty
@JsonInclude(JsonInclude.Include.NON_NULL)//username为空时不返回
private String username;
//返回数据忽略pwd
@JsonIgnore
private String pwd;
//指定日期格式
@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss",locale = "zh",timezone = "GMT+8")
private Date birthday;
private int age;
private int id;
//指定别名---应用场景返回数据不想让其知道意义
@JsonProperty("telephone")
private String phone;
json:
{“birthday”:“2020-02-11 04:14:28”,“age”:19,“id”:1,“telephone”:“13699466368”}
注:更多注解详情可参考https://blog.csdn.net/zhouyecheng/article/details/79562425
2.Jackson序列化与反序列化
pojo:
public class Student {
@JsonInclude(JsonInclude.Include.NON_NULL)
private String username;
//返回数据忽略pwd
@JsonIgnore
private String pwd;
//指定日期格式
@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss",locale = "zh",timezone = "GMT+8")
private Date birthday;
private int age;
private int id;
//指定别名---应用场景返回数据不想让其知道意义
@JsonProperty("telephone")
private String phone;
public Date getBirthday()
{
return this.birthday;
}
public void setBirthday(Date birthday)
{
this.birthday=birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
//jackson
@org.junit.Test
public void TestJackSon() throws Exception
{
//用map对象存储
Map<String, Object> map = new HashMap<>(16);
String s = "{\"id\": 1,\"name\": \"小明\",\"array\": [\"1\", \"2\"]," +
"\"test\":\"I'm test\",\"base\": {\"major\": \"物联网\",\"class\": \"3\"}}";
ObjectMapper mapper=new ObjectMapper();
map = mapper.readValue(s, map.getClass());
//获取id
Integer studentId = (Integer) map.get("id");
System.out.println(map.get("name"));
System.out.println(map.get("array").toString());
System.out.println(studentId);
//****************************************************************************************************************************
//student对象Json字符串
String s2="{\"birthday\":\"2020-02-11 03:29:11\",\"age\":19,\"id\":1,\"telephone\":\"13699466368\"}";
Student stu=new Student();
stu= mapper.readValue(s1, stu.getClass());
System.out.println(stu.getUsername()+stu.getPhone()+stu.getBirthday());
String s2 = mapper.writeValueAsString(stu);
System.out.println(s2);
}
输出:
更多推荐
已为社区贡献1条内容
所有评论(0)