jackson xml 反序列化 inline array
2022-09-04 19:21:51
如何反序列化这种奇怪的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”])'
我不想要一个简单的字符串列表。我两者都需要:名称和值。因此,我萌生了通过创建自己的反序列化器来使用a的想法......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 流中向后迭代?该方法如何知道何时停止?我不知道。