skip to Main Content

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.

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. I would suggest to serialize it into Map<String, Object> it will always work, but than you have to analyze your map and see what the structure is.

    You can use Json Jackson library directly and use class ObjectMapper to do so. Also you can use JsonUtils class which is a thin wrapper over ObjectMapper class and allows you to do simple serialization/deserialization in one line. Here is an example:

    try {
        Map<String, Object> myMap = JsonUtils.readObjectFromJsonString(jsonString, Map.class);
    catch(IOException ioe) {
      ...
    }
    

    JsonUtils class is available as part of Open Source MgntUtils java library written and maintained by me. Here is JsonUtils Javadoc and the library may be obtained as maven artifact or from github (including source code and Javadoc)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search