📜  Jackson注释-@JsonAnySetter

📅  最后修改于: 2020-11-16 07:37:18             🧑  作者: Mango


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

输出

Mark 
1