2015-05-01 85 views
0

我有一個複雜的對象,對於一些嵌套的對象,我需要將它們序列化爲JSON字段而不是JSON對象。Jackson Custom Serializer for class with annotations

例如,

public class Outer { 
    private String someField; 
    private AnotherClass anotherField; 
} 

public class AnotherClass { 
    @XmlElement(name = "useThisName") 
    private String someField; 
    private String anotherField; 
} 

我該如何製作一個自定義序列化程序,它將用於嵌套對象並服從註釋以便字段被正確命名?

我的用例是使用ObjectMapper.convertValue()方法創建Map,以便我可以遍歷它併爲其他網址創建NameValuePairs

最終我希望我可以遍歷一個

Map<String, String> 

落得和創建阿帕奇BasicNameValuePairs

下面是我想用於最終結果的一些代碼,如果我可以正確序列化所有內容。

Map<String, String> parameters 
     = DefaultJacksonMapper.getDefaultJacksonMapper().convertValue(obj, LinkedHashMap.class); 

     return parameters 
     .entrySet() 
     .stream() 
     .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue())) 
     .collect(Collectors.toList()); 

如果我將它轉換爲一個地圖,現在我的輸出是這樣的:

"someField" -> "data" 
"anotherField" -> "size = 2" 

我試圖讓Map有以下輸出,我覺得我需要自定義序列。

"someField" -> "data" 
"useThisName" -> "data" 
"anotherField" -> "data" 
+0

問題在哪裏? – ChristofferPass

+0

我加了。對不起,我分心了。 – twreid

+0

但是,當您將JSON反序列化爲Object時,它不會反映原始結構。爲什麼你想要將所有嵌套的字段合併到一個JSON對象中?如果您可以更多地解釋您的需求,我們可能會嘗試提出更好的解決方案。 – K139

回答

1

好的我想通了。

我最終創建了一個從SimpleModule繼承的新模塊。然後,我創建了一個新的抽象類像

public abstract class OuterMixin { 
    @JsonUnwrapped 
    private AnotherClass anotherField; 
} 

我也不得不註釋AnotherClass與JsonProperty像:

public class AnotherClass { 
    @XmlElement(name = "useThisName") 
    @JsonProperty("useThisName") 
    private String someField; 
    private String anotherField; 
} 

的時候我得到了我剛剛註冊我的模塊,它在我的對象映射,也做了轉換,這一切都奏效了。

作爲一個方面說明,我有另一個屬性,我不得不編寫一個自定義序列化程序和@JsonUnwrapped沒有與該工作。