Jackson注释 - @JsonAnySetter


@JsonAnySetter允许 setter 方法使用 Map,然后使用 Map 以与其他属性类似的方式反序列化 JSON 的附加属性。

示例@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; 

public class JacksonTester {
   public 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; 
   public Student(){ 
      properties = new HashMap<>(); 
   }  
   public Map<String, String> getProperties(){ 
      return properties; 
   } 
   @JsonAnySetter 
   public void add(String property, String value){ 
      properties.put(property, value); 
   }   
}

输出

Mark 
1