2

我正在JsonDeserialzer为 POJO 类写一个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类型,它可以是列表、字符串或任何东西。

我应该如何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;
    }

}
4

1 回答 1

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;
        }
    }
于 2016-01-15T04:58:45.030 回答