简体   繁体   中英

In Java, how can I map a string that is either JSON or XML to the same POJO, but with the XML having one different field/attribute name from the JSON?

I am currently using Jackson's XmlMapper and ObjectMapper. I want to map the string to a POJO (I think I'm using that term correctly) that has a private field with the same name as the JSON string's field. The XML string has a different name for the same field/attribute, and I want to use the JSON field name.

I also want to essentially "ignore" that field (while keeping it) and store it as something like a JsonNode, as the value of that field can be some complex, nested value without a known shape.

Example:

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
}

The JSON might look like this:

{
    "innerValue": {
        "data": {
            ... complex stuff
        },
        "otherValue": "more stuff"
    },
    "firstValue": "thingy"
}

The XML might look like this:

<result>
  <innerValue>
    <incorrectName>
      ... complex stuff
    </incorrectName>
    <otherValue>more stuff</otherValue>
  </innerValue>
  <firstValue>thingy</firstValue>
</result>

So the goal is to get the XML to work with that class, including both mapping incorrectName to the class' data , as well as storing the complex inner part as something like a JsonNode since I don't have a class to model it.

I have the JSON working with new ObjectMapper().readValue(jsonString, OuterClass.class) , and I think the XML should work with new XmlMapper().readValue(xmlString, OuterClass.class) , but I don't know where to go with annotations. I've looked at the different annotations available and I don't think I've found the right one. I've also read that I shouldn't convert XML to a JsonNode, as there can be problems with that. I don't need to convert it back to XML after, though, and can treat it as JSON once I receive the JSON/XML string. So, I'd appreciate some help, thanks!

@XmlAccessorType(XmlAccessType.PROPERTY)
public static class InnerClass {

    private JsonNode data;    // complex, nested, so no POJO to map to
    private String otherValue;

    // ... getters/setters
    @XmlElement(name = "incorrectName")
    protected JsonNode getData() {return data;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM