2

I am writing a JsonDeserialzer for a POJO class Attribute:

public class AttributeDeserializer extends JsonDeserializer<Attribute> {

        @Override
        public Attribute deserialize(JsonParser jp, DeserializationContext ctxt) 
          throws IOException, JsonProcessingException {

            JsonNode node = jp.getCodec().readTree(jp);

            String name =  node.get("name").asText();

            //String value = node.get("value").asText();

            Attribute attr = new Attribute();
            attr.setName(name);
            attr.setValue(value);

            return attr;
        }

Attribute class has two variables name and value where name is String type and value is Object type.

I know to get the String value from JsonNode using

node.get("name").asText()

, but value being Object type it can be a List, String or anything.

How shall I create the Attribute object in the deserialzer ??

Attribute class:

public class Attribute {

    protected String name;
    protected Object value;

    public String getName() {
        return name;
    }
    public void setName(String value) {
        this.name = value;
    }

    public Object getValue() {
        return value;
    }
    public void setValue(Object value) {
        this.value = value;
    }

}
Siddharth Trikha
  • 2,648
  • 8
  • 57
  • 101

1 Answers1

0

I solved it like this:

  public class AttributeDeserializer extends JsonDeserializer<Attribute> {

        @Override
        public Attribute deserialize(JsonParser jp, DeserializationContext ctxt) 
          throws IOException, JsonProcessingException {

            JsonNode node = jp.getCodec().readTree(jp);

            String longName = getLongName(node.get("name").asText());
            System.out.println("Translated name: " + name);

            ObjectMapper objMapper = new ObjectMapper();

            ObjectNode o = (ObjectNode)node;
            o.put("name", name);

            Attribute attr = objMapper.convertValue(o, Attribute.class);

            return attr;
        }
    }
Siddharth Trikha
  • 2,648
  • 8
  • 57
  • 101
  • 2
    The only problem with this, is if the object you are deserializing also has special deserializion behaviour, you will miss them as you are using a new `ObjectMapper` - This can be solved in a similar matter to http://stackoverflow.com/questions/18313323/how-do-i-call-the-default-deserializer-from-a-custom-deserializer-in-jackson – Uri Shalit Jan 15 '16 at 07:16