文章目录
记录下Jackson常用的功能
Jackson组成
jackson是java处理json的标准库
Jackson核心有三个包
core,annotation,databind, databind依赖前两者,所以使用时直接引入databind即可
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.0</version>
</dependency>
JSON和对象系列
JSON和POJO互转示例
使用ObjectMapper进行JSON字符串和类,List,Map的互转,字段若私有,则需提供getter和setter方法
ObjectMapper objectMapper = new ObjectMapper();
Information information = new Information();
information.setHost("12414142");
information.setN ame("111");
information.setPassword("123");
Email email = new Email();
email.setTitle("email-1");
email.setInformation(information);
String string = objectMapper.writeValueAsString(email);
System.out.println(string);
Email email1 = objectMapper.readValue(string, Email.class);
System.out.println(email1);
List<Car> listCar = objectMapper.readValue(jsonCarArray, new TypeReference<List<Car>>(){
});
Map<String, Object> map
= objectMapper.readValue(json, new TypeReference<Map<String,Object>>(){
});
public class Email {
private Information information;
private String title;
public Information getInformation() {
return information;
}
public void setInformation(Information information) {
this.information = information;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
public class Information {
private String name;
private String password;
private String host;
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 String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
}
// Note: can use getters/setters as well; here we just use public fields directly:
public class My