【发布时间】:2019-11-28 07:36:04
【问题描述】:
我目前正在使用 Jackson 的 XmlMapper 和 ObjectMapper。我想将字符串映射到 POJO(我认为我正确使用了该术语),该 POJO 具有与 JSON 字符串字段同名的私有字段。 XML 字符串对同一字段/属性有不同的名称,我想使用 JSON 字段名称。
我还想基本上“忽略”该字段(同时保留它)并将其存储为类似 JsonNode 的东西,因为该字段的值可以是一些复杂的嵌套值,没有已知的形状。
例子:
public static class OuterClass {
private String firstValue;
private InnerClass innerValue;
// ... getters/setters
}
public static class InnerClass {
private JsonNode data; // complex, nested, so no POJO to map to
private String otherValue;
// ... getters/setters
}
JSON 可能如下所示:
{
"innerValue": {
"data": {
... complex stuff
},
"otherValue": "more stuff"
},
"firstValue": "thingy"
}
XML 可能如下所示:
<result>
<innerValue>
<incorrectName>
... complex stuff
</incorrectName>
<otherValue>more stuff</otherValue>
</innerValue>
<firstValue>thingy</firstValue>
</result>
所以目标是让 XML 与该类一起工作,包括将 incorrectName 映射到类'data,以及将复杂的内部部分存储为 JsonNode 之类的东西,因为我没有一个类来建模它。
我有 JSON 与 new ObjectMapper().readValue(jsonString, OuterClass.class) 一起使用,我认为 XML 应该与 new XmlMapper().readValue(xmlString, OuterClass.class) 一起使用,但我不知道在哪里使用注释。我查看了可用的不同注释,但我认为我没有找到正确的注释。我还读到我不应该将 XML 转换为 JsonNode,因为这样做可能会出现问题。不过,之后我不需要将其转换回 XML,并且一旦我收到 JSON/XML 字符串就可以将其视为 JSON。所以,我会很感激一些帮助,谢谢!
【问题讨论】: