如何反序列化这种奇怪的 XML。在我看来,缺少道具实体(围绕道具),但我无法更改此 XML(Web 服务)的来源。
<parents>
<parent name="first">
<description><![CDATA[Description for the first-Entity]]></description>
<prop name="level">
<value><![CDATA[1]]></value>
</prop>
<prop name="enabled">
<value><![CDATA[true]]></value>
</prop>
<prop name="version">
<value><![CDATA[1.0-beta3]]></value>
</prop>
</parent>
<parent name="second">...</parent>
...
</parents>
我的实体是
public class Test {
@Test
public void deserializerTest() throws JsonParseException, JsonMappingException, IOException {
ObjectMapper om = new XmlMapper();
List<Parent> xml = om.readValue(new File("./test.xml"),
new TypeReference<List<Parent>>() {});
}
}
public class Prop {
@JacksonXmlProperty(isAttribute = true)
public String name;
@JacksonXmlText
public String value;
}
@JacksonXmlRootElement
public class Parent {
@JacksonXmlProperty(isAttribute = true)
public String name;
public String description;
// 1. alternative with List
public List<Prop> prop;
// 2. alternative with Map
@JsonDeserialize(using = PropDeser.class)
public Map<String, String> prop;
}
public static class PropDeser extends JsonDeserializer<Map<String, String>> {
@Override
public Map<String, String> deserialize(JsonParser jp,
DeserializationContext ctxt) throws IOException,
JsonProcessingException {
Map<String, String> ret = new HashMap<String, String>();
boolean eof = false;
while (jp.hasCurrentToken()) {
JsonToken t = jp.getCurrentToken();
switch (t) {
case END_OBJECT:
if (eof) {
return ret;
}
eof = true;
break;
case VALUE_STRING:
ret.put(jp.getCurrentName(), jp.getText());
break;
default:
eof = false;
break;
}
jp.nextValue();
}
return null;
}
}
1.替代
创建一个异常'无法从 JSON 字符串实例化类型 [简单类型,类 my.test.Prop] 的值;没有单字符串构造函数/工厂方法(通过引用链:my.test.Parent["prop"])'
我不想要一个简单的字符串列表。我需要两者:名称和价值。所以我想到了Map<String, String>
通过创建自己的反序列化器来使用...
2.替代
该错误似乎是 PropDeser.deserialize() 方法消耗了父级的结束标记。
java.lang.NullPointerException
at com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap.find(BeanPropertyMap.java:160)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:287)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:112)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:226)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:203)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:23)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2575)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:1766)
at my.test.Test.deserializerTest(Test.java:57)
是否有可能在XML-stream中向后迭代?该方法如何知道何时停止?我没有任何线索。