Deserializar en un HashMap de objetos personalizados con jackson


Tengo la siguiente clase:

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
}

Cuando ejecute el siguiente código:

    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(); 
    }

La cadena json producida se ve así:

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

Mi problema es conseguir que la cadena json anterior se deserizlice de nuevo en un

HashMap<String, Theme> 

Objeto.

Mi código de serialización se ve así:

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

Que des-serializa en un HashMap con las claves correctas, pero no crea objetos Theme para los valores. No se que especificar en vez de "HashMap.class " en el método readValue ().

Cualquier ayuda sería apreciada.

Author: wbj, 2013-08-01

3 answers

Debe crear un tipo de mapa específico y proporcionarlo en el proceso de deserialización:

TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Theme.class);
HashMap<String, Theme> map = mapper.readValue(json, mapType);
 74
Author: Michał Ziober,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-02 10:13:25

Puede usar la clase TypeReference que realiza la conversión de tipos para map con tipos definidos por el usuario. Más documentación en http://wiki.fasterxml.com/JacksonInFiveMinutes

ObjectMapper mapper = new ObjectMapper();
Map<String,Theme> result =
  mapper.readValue(src, new TypeReference<Map<String,Theme>>() {});
 15
Author: user2824471,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-10 18:22:47

Puedes hacer un POJO que extienda un Mapa.

Esto es importante para tratar con mapas anidados de objetos.

{
  key1: { nestedKey1: { value: 'You did it!' } }
}

Esto puede ser deserializado a través de:

class Parent extends HashMap<String, Child> {}

class Child extends HashMap<String, MyCoolPojo> {}

class MyCoolPojo { public String value; }

Parent parent = new ObjectMapper().readValue(json, Parent.class);
parent.get("key1").get("nestedKey1").value; // "You did it!"
 0
Author: 00500005,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-16 00:00:30