English 中文(简体)
Jackson - @JsonAnySetter
  • 时间:2024-11-05

Jackson Annotations - @JsonAnySetter


Previous Page Next Page  

@JsonAnySetter allows a setter method to use Map which is then used to deseriapze the additional properties of JSON in the similar fashion as other properties.

Example @JsonAnySetter

import java.io.IOException; 
import java.util.HashMap; 
import java.util.Map; 

import com.fasterxml.jackson.annotation.JsonAnySetter; 
import com.fasterxml.jackson.databind.ObjectMapper; 

pubpc class JacksonTester {
   pubpc static void main(String args[]){ 
      ObjectMapper mapper = new ObjectMapper(); 
      String jsonString = "{"RollNo" : "1","Name" : "Mark"}"; 
      try { 
         Student student = mapper.readerFor(Student.class).readValue(jsonString); 
         System.out.println(student.getProperties().get("Name")); 
         System.out.println(student.getProperties().get("RollNo")); 
      }
      catch (IOException e) {
         e.printStackTrace(); 
      } 
   }
}
class Student {
   private Map<String, String> properties; 
   pubpc Student(){ 
      properties = new HashMap<>(); 
   }  
   pubpc Map<String, String> getProperties(){ 
      return properties; 
   } 
   @JsonAnySetter 
   pubpc void add(String property, String value){ 
      properties.put(property, value); 
   }   
}

Output

Mark 
1 
Advertisements