2014-07-08 13 views
4

我有一個類,它看起來像這樣:如何與傑克遜序列基於java.util.Map類

@JsonFormat(shape=JsonFormat.Shape.OBJECT) 
public class MyMap implements Map<String, String> 
{ 
    protected Map<String, String> myMap = new HashMap<String, String>(); 

    protected String myProperty = "my property"; 
    public String getMyProperty() 
    { 
     return myProperty; 
    } 
    public void setMyProperty(String myProperty) 
    { 
     this.myProperty = myProperty; 
    } 

    // 
    // java.util.Map mathods implementations 
    // ... 
} 

而與此代碼主要方法:

  MyMap map = new MyMap(); 
      map.put("str1", "str2"); 

      ObjectMapper mapper = new ObjectMapper(); 
      mapper.getDeserializationConfig().withAnnotationIntrospector(new JacksonAnnotationIntrospector()); 
      mapper.getSerializationConfig().withAnnotationIntrospector(new JacksonAnnotationIntrospector()); 
      System.out.println(mapper.writeValueAsString(map)); 

當執行此代碼我得到以下輸出:{「str1」:「str2」}

我的問題是爲什麼內部屬性「myProperty」沒有與地圖序列化? 應該做些什麼來序列化內部屬性?

回答

3

很可能你最終會實現你自己的序列化器,它將處理你自定義的Map類型。有關更多信息,請參閱this question

如果選擇成分來替代繼承,那就是讓你的類包括地圖領域不延長地圖的話,是很容易解決這個使用the @JsonAnyGetter annotation

下面是一個例子:

public class JacksonMap { 

    public static class Bean { 
     private final String field; 
     private final Map<String, Object> map; 

     public Bean(String field, Map<String, Object> map) { 
      this.field = field; 
      this.map = map; 
     } 

     public String getField() { 
      return field; 
     } 

     @JsonAnyGetter 
     public Map<String, Object> getMap() { 
      return map; 
     } 
    } 

    public static void main(String[] args) throws JsonProcessingException { 
     Bean map = new Bean("value1", Collections.<String, Object>singletonMap("key1", "value2")); 
     ObjectMapper mapper = new ObjectMapper(); 
     System.out.println(mapper.writeValueAsString(map)); 
    } 
} 

輸出:

{"field":"value1","key1":"value2"} 
+0

由於阿列克謝。我選擇嘗試構圖模式,並完成了這項工作。只需要注意一點,我不需要爲我的地圖獲取器使用@JsonAnyGetter註釋。 – odavid

+1

@odavid好!請注意,如果您不使用JsonAnyGetter,那麼您的json看起來像:{「field」:「value1」,「map」:{「key1」:「value2」}} –