Search code examples
javajsonjacksondeserialization

I would like to deserialize JSON , in which one field may have more than one dataType


I would like to deserialize a JSON body in java, in which one field may have more than one dataType and different field.

For example :

1st Variant

{
    "errorMessage": " Task timed out after 60.04 seconds"
}

2nd Variant

{
    "errorType": "Runtime.ExitError",
    "errorMessage": "RequestId: xyz Error: Runtime exited with error: signal: aborted"
}

3rd Variant

 "errorMessage": {
        "code": 502,
        "message": "Failed to read object from S3: abcd9.json with error message: NoSuchBucket: The specified bucket does not exist"
    },
    "errorType": "Error",

I am confuse how to design a pojo or data model to handle this and deserialize.

If its 3rd type of the JSON I want to access the code and message in my class.

I was trying to create a customDeserializer but didn't get success.


Solution

  • Usually there is a structure and pattern to these things and you would not need a Pojo for every variation, but your examples seem off to me, are you sure this is exactly what you are receiving?

    Typically your variants could be covered using something like below.

    public class ErrorRoot {
        public String errorType;
        public String errorMessage;
    }
    

    OR

    public class ErrorRoot {
        public ErrorMessage errorMessage;
        public String errorType;
    }
    
    public class ErrorMessage {
        public int code;
        public String message;
    }
    

    Usage:

    // Using fasterxml.jackson
    ObjectMapper om = new ObjectMapper();
    Root root = om.readValue(myJsonString, ErrorRoot.class);