gpt4 book ai didi

jackson - 让 Jackson XMLMapper 读取根元素名称

转载 作者:行者123 更新时间:2023-12-01 23:01:30 31 4
gpt4 key购买 nike

如何让 Jackson 的 XMLMapper 在反序列化时读取根 xml 元素的名称?

我正在将输入 XML 反序列化为通用 Java 类、LinkedHashMap,然后反序列化为 JSON。我想在反序列化到 LinkedHashMap 时动态读取输入 XML 的根元素。

代码

XmlMapper xmlMapper = new XmlMapper();
Map entries = xmlMapper.readValue(new File("source.xml"), LinkedHashMap.class);
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writer().writeValueAsString(entries);
System.out.println(json);

输入 XML

<?xml version="1.0" encoding="ISO-8859-1"?>
<File>
<NumLeases>1</NumLeases>
<NEDOCO>18738</NEDOCO>
<NWUNIT>0004</NWUNIT>
<FLAG>SUCCESS</FLAG>
<MESSAGE>Test Upload</MESSAGE>
<Lease>
<LeaseVersion>1</LeaseVersion>
<F1501B>
<NEDOCO>18738</NEDOCO>
<NWUNIT>0004</NWUNIT>
<NTRUSTRECORDKEY>12</NTRUSTRECORDKEY>
</F1501B>
</Lease>
</File>

实际输出

{"NumLeases":"1","NEDOCO":"18738","NWUNIT":"0004","FLAG":"SUCCESS","MESSAGE":"Test Upload","Lease":{"LeaseVersion":"1","F1501B":{"NEDOCO":"18738","NWUNIT":"0004","NTRUSTRECORDKEY":"12"}}}  

预期输出(注意:JSON 中有一个名为“File”的根元素)

{"File":{"NumLeases":"1","NEDOCO":"18738","NWUNIT":"0004","FLAG":"SUCCESS","MESSAGE":"Test Upload","Lease":{"LeaseVersion":"1","F1501B":{"NEDOCO":"18738","NWUNIT":"0004","NTRUSTRECORDKEY":"12"}}}}

可能有一些开关可以设置它。任何帮助将不胜感激。

最佳答案

遗憾的是没有相应的标志。这可以通过 com.fasterxml.jackson.databind.deser.std.JsonNode Deserializer 的自定义实现来完成。 ( Jackson How-To: Custom Deserializers ):

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.deser.FromXmlParser;
import java.io.File;
import java.io.IOException;
//...
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.registerModule(new SimpleModule().addDeserializer(JsonNode.class,

new JsonNodeDeserializer() {

@Override
public JsonNode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String rootName = ((FromXmlParser)p).getStaxReader().getLocalName();
return ctxt.getNodeFactory()
.objectNode().set(rootName, super.deserialize(p, ctxt));
}
}));

JsonNode entries = xmlMapper.readTree(new File("source.xml"));
System.out.println(entries);

关于jackson - 让 Jackson XMLMapper 读取根元素名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36317162/

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