简体   繁体   中英

Java Deserialization when JSON attribute data varies wildly

Task at hand: Consider the following model for a JSON response, every API response will conform to this response, obviously the data will vary. Lets call it ResponseModel:

{
    "isErroneous": false,
    "Message": "",
    "Result": null,
    "Data": {
        "objId": 38,
        "objName": "StackO",
        "objDescription": "StackODesc",
        "objOtherId": 0,
        "objLocationId": 1
    }
}

How can I deserialize this response regardless of the data in Data: ? Data could contain a single object of different types, eg a Dog, a Car. It could also contain a collection of Cars or Dogs eg not just one like above.

It could also contain A car, the cars engine obj, the cars driver seat obj.

In short, the same response is always going to be present but the value of Data can vary wildly, I want to try best to deserialize this to some sort of Result.class for ALL possible scenarios, how do I best approach this? Setting up the class ResponseModel.class is easy for everything except the "Data" type.

Thanks

Here is another example of something which could be returned

{
    "isErroneous": false,
    "Message": "",
    "Result": null,
    "Data": [
        {
            "carId": 1,
            "carName": "car#1",
            "carDescription": "car#1",
            "carOtherId": 1,
        },
        {
            "carId": 2,
            "carName": "car#2",
            "carDescription": "car#2",
            "carOtherId": 2,
        },
        {
            "carId": 3,
            "carName": "car#3",
            "carDescription": "car#3",
            "carOtherId": 3,
        },

As you can see in the second example, we are returning a list of cars but in the first response we are just returning a single object. Am i trying to abstract this too much? should I setup custom response(s) for each call of the API etc?

I need to be writing integration tests asserting that the deserialized object is equal to one that I expect everytime.

you can try to check if your json input contains "Data": { or "Data": [ then parse it to seperate class accordingly

But... maybe it's not the best way to do it

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