对象的JsonNode?

时间:2016-01-14 09:51:02

标签: java json jackson objectmapper

我正在为POJO班级JsonDeserialzer撰写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类有两个变量namevalue,其中名称为String类型,值为Object类型。

我知道使用

JsonNode获取字符串值
node.get("name").asText()

,但值为Object,可以是List,String或其他任何内容。

如何在反序列化器中创建Attribute对象?

属性类:

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

}

1 个答案:

答案 0 :(得分:0)

我解决了这个问题:

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