Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing json from retrofit using jackson where same variable name can represent two different objects

The response from retrofit2 may be of the following types.(and we don't know before hand which response will come)

{
    "id": "abc",
    "place": "LA",
    "driverId": "abbabaaan"
}

or

{
    "id": "abc",
    "place": "LA",
    "driverId": {
        "name": "xyz",
        "id": "jygsdsah",
        "car": "merc"
    }
}

Is there any way to define a class so that while deserializing jackson will check the type of object "driverId" contains and assigns it to say "driverIdObj" field or "driverIdStr" field in the class.

like image 460
Debanjan Avatar asked Jun 03 '26 05:06

Debanjan


1 Answers

You could deserialize to a Map. Afterwards, you could inspect the map and decide to which of the 2 types you convert the map. Take a look at this answer: Deserializing JSON based on object type

To convert from Map to Object you can use ObjectMapper::convertValue, e.g

 mapper.convertValue(map, Response1.class)
like image 98
Lucian Avatar answered Jun 05 '26 19:06

Lucian