2

次の JSON の例があるとします。

{
    "title" : "tttt",
    "custom" : {
        "a" : "aaaaa",
        "b" : "bbbbb",
        "c" : { 
            "d" : "dddd"
        }
    }
}

これを次のクラスに逆シリアル化したい:

public class Article {
    private String title;
    private String custom;

    public void setTitle(String title) { this.title = title; }
    public String getTitle() { return title; }
    public void setCustom(String custom) { this.custom = custom; }
    public String getCustom() { return custom; }        
}

私が望む結果は、タイトルが通常どおり逆シリアル化されることですが、「カスタム」の下のjsonサブツリーは逆シリアル化されず、生のjson文字列として設定されます。

ObjectMapper mapper = new ObjectMapper();
Article article = mapper.readValue(content, Article.class);
assertEquals(article.getTitle(), "tttt");
assertEquals(article.getCustom(),
   "{\"a\" : \"aaaaa\","        +
        "\"b\" : \"bbbbb\","    +
        "\"c\" : {"             + 
            "\"d\" : \"dddd\" " +
        "}"                     +
    "}"); 

もう 1 つの重要な注意点は、カスタム ノードの下にある元の JSON を変更して、エスケープされた json を使用することはできないため、文字列として扱われることです。

4

3 に答える 3

3

少し楽な方法を見つけました。dto next セッターに追加するだけです。

public void setCustom(JsonNode custom) { this.custom = custom.toString(); }

単純な文字列として取得するには、次のように注釈を付けます@JsonRawValue

于 2015-02-20T11:07:20.610 に答える
1

カスタムを書くことができますDeserializer

このSOの質問を参照してください

于 2013-10-17T23:09:26.813 に答える