我正在为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
,可以是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;
}
}
答案 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;
}
}