56

私は次のクラスを持っています:

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

import java.io.Serializable;
import java.util.HashMap;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Theme implements Serializable {

    @JsonProperty
    private String themeName;

    @JsonProperty
    private boolean customized;

    @JsonProperty
    private HashMap<String, String> descriptor;

    //...getters and setters for the above properties
}

次のコードを実行すると:

    HashMap<String, Theme> test = new HashMap<String, Theme>();
    Theme t1 = new Theme();
    t1.setCustomized(false);
    t1.setThemeName("theme1");
    test.put("theme1", t1);

    Theme t2 = new Theme();
    t2.setCustomized(true);
    t2.setThemeName("theme2");
    t2.setDescriptor(new HashMap<String, String>());
    t2.getDescriptor().put("foo", "one");
    t2.getDescriptor().put("bar", "two");
    test.put("theme2", t2);
    String json = "";
    ObjectMapper mapper = objectMapperFactory.createObjectMapper();
    try {
        json = mapper.writeValueAsString(test);
    } catch (IOException e) {
        e.printStackTrace(); 
    }

生成される json 文字列は次のようになります。

{
  "theme2": {
    "themeName": "theme2",
    "customized": true,
    "descriptor": {
      "foo": "one",
       "bar": "two"
    }
  },
  "theme1": {
    "themeName": "theme1",
    "customized": false,
    "descriptor": null
  }
}

私の問題は、上記のjson文字列をデシリアライズして元に戻すことです

HashMap<String, Theme> 

物体。

私の逆シリアル化コードは次のようになります。

HashMap<String, Themes> themes =
        objectMapperFactory.createObjectMapper().readValue(json, HashMap.class);

正しいキーを使用して HashMap に逆シリアル化しますが、値の Theme オブジェクトを作成しません。readValue() メソッドの「HashMap.class」の代わりに何を指定すればよいかわかりません。

どんな助けでも大歓迎です。

4

3 に答える 3

29

ユーザー定義型のマップの型キャストを行う TypeReference クラスを使用できます。https://github.com/FasterXML/jackson-databind/のその他のドキュメント

ObjectMapper mapper = new ObjectMapper();
Map<String,Theme> result =
  mapper.readValue(src, new TypeReference<Map<String,Theme>>() {});
于 2013-09-27T17:35:11.173 に答える