JsonNode 到对象?

问题描述 投票:0回答:1

我正在为 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
类有两个变量
name
value
,其中名称是
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;
    }

}
java json jackson objectmapper
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;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.