我正在为POJO类Attribute编写JsonDeserialzer
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,其中name是String类型,value是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;
}
}发布于 2016-01-15 12:58:45
我是这样解决的:
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;
}
}https://stackoverflow.com/questions/34786342
复制相似问题