2017-01-11 40 views
1

我想創建一個休息終點並使用揚鞭作爲UI表示。我使用它,其中POJO具有@JsonIgnore註釋的變量,如下所示。如何繞過@JsonIgnore註釋?

@JsonIgnore 
private Map<String, Object> property = new HashMap<String, Object>(); 

現在,當我提供JSON(帶屬性值)這個終點,並試圖讀取它的值是出來爲null(由於@JsonIgnore)。

pojoObj.getProperties(); //null 

有沒有什麼辦法,如果我可以不刪除@JsonIgnore註釋得到財產價值?

回答

3

這可以通過利用傑克遜的Mixin功能,您創建了另一類取消忽略註釋來實現。然後,您可以在「附加」的混入到ObjectMapper在運行時:

這是我用過的POJO:

public class Bean 
{ 
    // always deserialized 
    public String name; 

    // ignored (unless...) 
    @JsonIgnore 
    public Map<String, Object> properties = new HashMap<String, Object>(); 
} 

這是「其他」類。這只是與相同屬性名稱的另一個POJO

public class DoNotIgnore 
{ 
    @JsonIgnore(false) 
    public Map<String, Object> properties; 
} 

傑克遜模塊用於豆拴在混入:

@SuppressWarnings("serial") 
public class DoNotIgnoreModule extends SimpleModule 
{ 
    public DoNotIgnoreModule() { 
     super("DoNotIgnoreModule"); 
    } 

    @Override 
    public void setupModule(SetupContext context) 
    { 
     context.setMixInAnnotations(Bean.class, DoNotIgnore.class); 
    } 
} 

綁一起:

public static void main(String[] args) 
{ 
    String json = "{\"name\": \"MyName\"," 
      +"\"properties\": {\"key1\": \"val1\", \"key2\": \"val2\", \"key3\": \"val3\"}" 
      + "}"; 

    try { 
     ObjectMapper mapper = new ObjectMapper(); 
     // decide at run time whether to ignore properties or not 
     if ("do-not-ignore".equals(args[0])) { 
      mapper.registerModule(new DoNotIgnoreModule()); 
     } 
     Bean bean = mapper.readValue(json, Bean.class); 
     System.out.println(" Name: " + bean.name + ", properties " + bean.properties); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
}