zoukankan      html  css  js  c++  java
  • @JsonProperty和@JsonAlias的区别

    @JsonProperty
    这个注解提供了序列化和反序列化过程中该java属性所对应的名称
    @JsonAlias
    这个注解只在反序列化时起作用,指定该java属性可以接受的更多名称

    代码展示下不同注解的效果:

    	public static void main (String[] args ) throws IOException {
            String a ="{"NaMe":"hello"}";
            ObjectMapper objectMapper = new ObjectMapper();
            Label label = objectMapper.readValue(a, Label.class);
            String labelString = objectMapper.writeValueAsString(label);
            System.out.println(labelString);
        }
    
        public static class Label{
        	//反序列化时两个都可用,都没有会报错
            //@JsonAlias("NaMe")
            @JsonProperty("NaMe")
            public String name;
            public Label(){
            }
        }
    

    使用@JsonProperty时,序列化结果为:{“NaMe”:“hello”}
    使用@JsonAlias时,序列化结果为:{“name”:“hello”}

    参考:https://www.concretepage.com/jackson-api/jackson-jsonproperty-and-jsonalias-example.
    ————————————————
    版权声明:本文为CSDN博主「_古井心」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/u010234516/article/details/84316340

    1. Technologies Used
      Find the technologies being used in our example.
    2. Java 9
    3. Jackson 2.9.4
    4. Gradle 4.3.1
    5. Eclipse Oxygen
    6. @JsonProperty
      @JsonProperty is a marker annotation to define logical property. @JsonProperty can be annotated at non-static setter or getter method or non-static object field. The logical property is used in serialization and de-serialization of JSON. @JsonProperty is annotated as following.
    7. Using object field.

    @JsonProperty("bookCategory")
    private String category;

    1. Using Getter method.
    @JsonProperty("bookCategory")	
    public String getCategory() {
       return category;
    } 
    
    1. Using Setter method.
    @JsonProperty("bookCategory")		
    public void setCategory(String category) {
        this.category = category;
    } 
    

    In all the above cases the logical property is bookCategory. If we do not assign any value to @JsonProperty, for example.

    @JsonProperty
    private String category;  
    

    Then logical property name is actual property name. In the above code, the logical property will be category. If we are not providing any value, then annotating @JsonProperty to a property is optional.
    3. @JsonProperty Elements
    The elements of @JsonProperty are as follows.
    value: Defines name of logical property.
    access: Changes the visibility of logical property in serialization and deserialization.
    defaultValue: It is used to document expected default value.
    index: Defines numerical index of the property related to other properties specified by object.
    required: Defines whether the value for the property is required or not during deserialization.
    3.1. @JsonProperty value
    value element defines the name of logical property.

    @JsonProperty(value= "bookCategory")	
    private String category; 
    

    If we are using only value element, we can assign logical property as following.

    @JsonProperty("bookCategory")	
    private String category; 
    

    3.2. @JsonProperty access
    access element changes the visibility of logical property defined by getter or setter or object field. The values of access can be one of followings.
    Access.WRITE_ONLY: The visibility of logical property will be only available when we set JSON data to Java object i.e. at the time of deserialization.
    Access.READ_ONLY: The visibility of logical property will be only available when we get JSON data from Java object i.e. at the time of serialization.
    Access.READ_WRITE: The visibility of logical property will be available at both the time serialization and deserialization.
    Access.AUTO: The visibility of logical property will be determined automatically which is the default value of access element.

    We can define it as follows.

    @JsonProperty(value= "bookCategory", access=Access.WRITE_ONLY)	
    private String category; 
    

    In the above code, the logical property bookCategory will be only available at the time of deserialization and not for serialization.
    4. @JsonProperty with Enum
    Here we will use @JsonProperty with Enum. Suppose we have defined Enum as given below.

    public enum Gender {
        @JsonProperty("male") GENDER_MALE,
        @JsonProperty("female") GENDER_FEMALE;
    } 
    

    Now when we serialize the above Enum using ObjectMapper as given below,

    ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(Gender.GENDER_FEMALE));

    The output will be

    "female"

    And if we do not use @JsonProperty then output will be

    "GENDER_FEMALE"

    1. @JsonAlias
      @JsonAlias is introduced in Jackson 2.9 release. @JsonAlias defines one or more alternative names for a property to be accepted during deserialization i.e. setting JSON data to Java object. But at the time of serialization i.e. while getting JSON from Java object, only actual logical property name is used and not alias. @JsonAlias is defined as follows.

    @JsonAlias({"bkcat", "mybkcat"})
    private String category;

    In the above code, the actual logical property is category and alias is bkcat and mybkcat. Now the above property will set value from JSON for JSON field name bkcat, mybkcat and category. If we are defining logical property using @JsonProperty, both @JsonProperty and @JsonAlias can be used as following.

    @JsonProperty("bookCategory")
    @JsonAlias({"bkcat", "mybkcat"})
    private String category;

    In the above code, the actual logical property is bookCategory and alias is bkcat and mybkcat. At the time of deserialization either JSON is

    {
    "bookCategory" : "Java"
    }

    Or JSON is

    {
    "bkcat" : "Java"
    }

    Or JSON is

    {
    "mybkcat" : "Java"
    }

    All above will set value in object property category. But when we serialization, we will get JSON only with actual logical property name as given below.

    {
    "bookCategory" : "Java"
    }

    1. Complete Example
    build.gradle
    
    apply plugin: 'java'
    apply plugin: 'eclipse'
    archivesBaseName = 'concretepage'
    version = '1' 
    repositories {
        mavenCentral()
    }
    dependencies {
        compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.4'
        compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.4'
        compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.9.4'
    } 
    
    Book.java
    
    package com.concretepage;
    import com.fasterxml.jackson.annotation.JsonAlias;
    import com.fasterxml.jackson.annotation.JsonProperty;
    public class Book {
    	@JsonProperty("bookName")		
    	private String name;
    	
    	@JsonProperty("bookCategory")	
    	@JsonAlias({"bkcat", "mybkcat"})
    	private String category;  
    	
      	public Book(){}
      	public Book(String name, String category) {
      		this.name = name;
      		this.category = category;
      	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getCategory() {
    		return category;
    	}
    	public void setCategory(String category) {
    		this.category = category;
    	}
    } 
    
    Writer.java
    
    package com.concretepage;
    import com.fasterxml.jackson.annotation.JsonAlias;
    import com.fasterxml.jackson.annotation.JsonProperty;
    public class Writer {
    	@JsonProperty("writerId")	
    	private Integer id; 
    	
    	@JsonProperty("writerName")
    	@JsonAlias({"wname", "mywname"})
    	private String name;
    	
    	@JsonProperty("writerBook")	
    	private Book book;
    
      	public Writer(){}
      	public Writer(Integer id, String name, Book book){
      		this.id = id;
      		this.name = name;
      		this.book = book;
      	}	
    	public Integer getId() {
    		return id;
    	}
    	public void setId(Integer id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public Book getBook() {
    		return book;
    	}
    	public void setBook(Book book) {
    		this.book = book;
    	}
    } 
    
    JSONToObject.java
    
    package com.concretepage;
    import java.io.IOException;
    import com.fasterxml.jackson.core.JsonParseException;
    import com.fasterxml.jackson.databind.JsonMappingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    public class JSONToObject {
    	public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    		 String jsonData = 
    			    "{"
    				  +""writerId" : 111,"
    				  +""mywname" : "Mahesh","
    				  +""writerBook" : {"
    				    +""bookName" : "Learning Spring","
    				    +""bkcat" : "Spring""
    				  +"}"
    			   +"}";
    		 ObjectMapper mapper = new ObjectMapper();
    		 Writer writer = mapper.readValue(jsonData, Writer.class);
    		 System.out.println(writer.getId()+", "+ writer.getName());
    		 Book book = writer.getBook();
    		 System.out.println(book.getName()+", "+ book.getCategory());
    	}
    } 
    

    Output

    111, Mahesh
    Learning Spring, Spring

    ObjectToJSON.java
    
    package com.concretepage;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    public class ObjectToJSON {
      public static void main(String[] args) throws JsonProcessingException {
         ObjectMapper mapper = new ObjectMapper();
         Book book = new Book("Learning Java", "Java");
         Writer writer = new Writer(110, "Mohit", book);
         String jsonWriter = mapper.writerWithDefaultPrettyPrinter()
    		 .writeValueAsString(writer);
         System.out.println(jsonWriter);
         
      }
    } 
    
    Output
    
    {
      "writerId" : 110,
      "writerName" : "Mohit",
      "writerBook" : {
        "bookName" : "Learning Java",
        "bookCategory" : "Java"
      }
    } 
    
    1. References
      Annotation Type JsonProperty
      Annotation Type JsonAlias
    2. Download Source Code
      jackson-jsonproperty-and-jsonalias-example.zip
  • 相关阅读:
    问题:plugin with id 'android' not found
    问题:plugin with id 'android' not found
    【NYOJ】[122]Triangular Sums
    【NYOJ】[122]Triangular Sums
    【NYOJ】[113]字符串替换
    【NYOJ】[113]字符串替换
    【NYOJ】[111]分数加减法
    【NYOJ】[111]分数加减法
    【NYOJ】[101]两点距离
    【NYOJ】[101]两点距离
  • 原文地址:https://www.cnblogs.com/fb010001/p/14964178.html
Copyright © 2011-2022 走看看