Jackson using summary

 

        // pom依赖       
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.8</version>
        </dependency>

Jackson's use of readValue and write

1.定义一个User对象
public class User {
     private String name;
     private int age;
     private Date birthday;  //   没有使用jackson注解将会变成时间戳
     private String email;
     
    public User(String name, int age, Date birthday, String email) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
        this.email = email;
   }

     public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  

    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 getEmail() {  
        return email;  
    }  
    public void setEmail(String email) {  
        this.email = email;  
    }  

  
}
2.使用jackson  的ObjectMapper 类中的 readValue()方法进行转换
public class JsonTest  
{  
     public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {  
         User user=new User("隔壁老王", 18, new Date(), "110");  
         User user1=new User("隔壁老王", 18, new Date(), "110");  
         List<User> list = new ArrayList<User>();
         list.add(user);
         list.add(user1);

        //转换器 
        ObjectMapper mapper = new ObjectMapper();  
          
        // 对象--json数据
        String json=mapper.writeValueAsString(user); //将对象转换成json 
        // 将json 字符串转成User类
        User u = mapper.readValue(json, User.class); 
       
       // 将json 字符串转化成List<User> 
       List<User> list1 = mapper.readValue(list, new TypeReference<List<People>>(){}f)
       // 其他的如将文件中转化成类的方法也相识 如 
      // readValue(File src, TypeReference valueTypeRef)
      // readValue(File src, Class<T> valueType)
    }
}
3.使用jackson  的ObjectMapper 类中的 writerValue()方法进行转换
public class JsonTest  
{  
     public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {  
         SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");  
         User user=new User("隔壁老王", 18, dateformat.parse("1996-10-01"), "110");  
         
         //转换器 
        ObjectMapper mapper = new ObjectMapper();  
        
        //User类转JSON 字符串
        String json = mapper.writeValueAsString(user);  
        System.out.println(json);  
       
        //Java集合转JSON 字符串 
        List<User> users = new ArrayList<User>();  
        users.add(user);  
        String jsonlist = mapper.writeValueAsString(users);  
        System.out.println(jsonlist);  
    }  

   }
}

4.使用jackson ObjectMapper获取具体json 字符串中某个key值对于的value
// 假设 json字符串格式为 {content:{rendered: "23"}, titile:{rendered: "别跑"}}  则获取方式如下:
 ObjectMapper mapper = new ObjectMapper();
            mapper.readTree(content).forEach(jsonNode -> {
                String renderedContent = jsonNode.path("content").path("rendered").asText("");
                String title = jsonNode.path("title").path("rendered").asText("");
            });
5.使用jackson  的提供了一系列注解
@JsonIgnore 此注解用于属性上,作用是进行JSON操作时忽略该属性。
@JsonFormat 此注解用于属性上,作用是把Date类型直接转化为想要的格式,如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")。
@JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化

Link: https: //www.jianshu.com/p/7e4bc9a535c8

Jackson notes and common usage

Recently wrote the project, use some of Jackson's notes, to sum up, to help you to remember.

1. @ JsonIgnore and @JsonIgnoreProperties

After two annotations may choose to use compared to controls:

@JsonIgnore

When json serialization java bean in some of the properties ignored , serialization and de-serialization are affected.

private String name;
private Integer age;
@JsonIgnore
private String color;

Print run in the console method

System.out.println(name+""+age+""+color+"");

Will only show the name and age, color is not affected notes are displayed.

Use Method: General marking property or method on, json returned data, i.e. does not contain the property.

@JsonIgnoreProperties

And the role of @JsonIgnore the same, which attributes are told that Jackson ignored,

Except @JsonIgnoreProperties is class level and may specify a plurality of attributes simultaneously.

 

@JsonIgnoreProperties(value = {"age","color"})

public class TestJackson {

    private String id;

    private String username;

    private String password;

    private Integer age;
    private String color;

 

}

 

Class age and color attributes will be ignored during serialization and de-serialization.

 

2.@JsonProperty

 

It is used on the property, the role of the name of the attribute name sequence into another

@JsonProperty("name")

private String username;

The username attribute is serialized as name

 

3.@JsonInclude(JsonInclude.Include.NON_NULL)

 

This annotation indicates, if the value is null, is not returned , the annotations may be added on the class, the entity class json when the mutual conversion, the attribute value is null does not participate in serialization .

 

@JsonInclude(JsonInclude.Include.NON_NULL)

public Vector children;

 

@JsonInclude(JsonInclude.Include.NON_NULL)

public class TestJackson {

                       xxxxxx

}
Links: https://www.cnblogs.com/koudaiyoutang/p/9709806.html

Guess you like

Origin blog.csdn.net/haoranhaoshi/article/details/91897729