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

后端 未结 4 1556
有刺的猬
有刺的猬 2021-01-21 09:46

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\",         


        
4条回答
  •  囚心锁ツ
    2021-01-21 10:10

    Make some special handling for the driverId field in your response class using the JsonNode class. Something like the following:

    public class Response {
        private String id, place, driverIdStr;
        private DriverIdObj driverIdObj;
    
        // ... Various getters and setters omitted.
    
        public void setDriverId(JsonNode driverId) {
            if (driverId.isObject()) {
                // Process the complex version of DriverId.
                driverIdObj = new DriverIdObj( /* retrieve fields from JsonNode */ );
            } else {
                // Process the simple version of DriverId
                driverIdStr = driverId.asText();
            }
        }
    }
    

    This lets you maintain a normal approach for most of the response, while making it possible to handle the special field with a minimum of pain.

提交回复
热议问题