gpt4 book ai didi

java - 无法使用 jackson 解析 xml 根元素

转载 作者:行者123 更新时间:2023-11-30 06:40:09 26 4
gpt4 key购买 nike

测试 Bean

@JacksonXmlRootElement(localName = "DATA_RECORD")
public class TestBean{
@JacksonXmlProperty(localName="ERROR_MESSAGE_CODE")
private String error_message_code;
@JacksonXmlProperty(localName="ERROR_MESSAGE")
private String error_message;
//...getter/setter
}

XML 示例

String xml = "<?xml version=\"1.0\" encoding=\"Windows-31J\" standalone=\"no\"?>"
+ "<Message xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
//+">"
+ "xsi:noNamespaceSchemaLocation=\"TEST.xsd\">" // if comment out this,it will work.
+ "<DATA_RECORD>"
+ "<ERROR_MESSAGE>some message</ERROR_MESSAGE>"
+ "<ERROR_MESSAGE_CODE>CODE111</ERROR_MESSAGE_CODE>"
+ "</DATA_RECORD>"
+ "</Message>";

反序列化

XmlMapper xmlMapper = new XmlMapper();
//xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
xmlMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
TestBean test = xmlMapper.readValue(xml, TestBean.class);
log.debug(test.toString());

我从 Junit 运行它,并得到如下异常:

Root name 'noNamespaceSchemaLocation' does not match expected ('DATA_RECORD') ....

如果我从 String xml 中删除 xsi:noNamespaceSchemaLocation="TEST.xsd",它将正常工作。

对此有什么想法吗?感谢您的帮助。

最佳答案

根据docs ,当您指定 UNWRAP_ROOT_VALUE 时,Jackson(此处为 XML,而不是 JSON)

Will verify that the root JSON value is a JSON Object, and that it has a single property with expected root name. If not, a JsonMappingException is thrown;

在这种情况下,根 Message 除了 DATA_RECORD 之外还有另一个属性,即名称为 noNamespaceSchemaLocation 的 XML 属性,并指定为 抛出 JsonMappingException

恐怕您必须解析Message并从那里获取TestBean。例如:

@JacksonXmlRootElement
class Message {
@JacksonXmlProperty(localName = "DATA_RECORD")
private TestBean dataRecord;
}

class TestBean {
@JacksonXmlProperty(localName = "ERROR_MESSAGE_CODE")
private String error_message_code;
@JacksonXmlProperty(localName = "ERROR_MESSAGE")
private String error_message;
}

xmlMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Message test = xmlMapper.readValue(xml, Message.class);
log.debug(test.getDataRecord().toString());

关于java - 无法使用 jackson 解析 xml 根元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44494142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com