read jsonvalue example deserialize java jackson json-deserialization

java - jsonvalue - spring objectmapper



Deserialización en un HashMap de objetos personalizados con jackson (3)

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

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 ejecuto 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 tiene este aspecto:

{ "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 des-serice de nuevo en una

HashMap<String, Theme>

objeto.

Mi código de dessialización tiene este aspecto:

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

Que se des-serializa en un HashMap con las teclas correctas, pero no crea objetos de Tema para los valores. No sé qué especificar en lugar de "HashMap.class" en el método readValue ().

Cualquier ayuda sería apreciada.


Puede usar la clase TypeReference que realiza la conversión de tipos para el mapa 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>>() {});


Puedes hacer un POJO que extienda un Mapa.

Esto es importante para tratar con mapas de objetos anidados.

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

Esto se puede deserializar 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!"