BATMAN_2008
BATMAN_2008

Reputation: 3530

How to make fields in type class mandatory based on the parent class during deserialization

I am trying to deserialize my JSON and everything is working fine but I would like to add few conditions to make it better.

Following is my Parent class based on which deserialize happen:

public class ParentJSON{
    @NotNull
    private String name;
    private ChildJSON type;
}

The field type is optional is JSON. However if the field type is present in JSON then I would like to make the fields in ChildJSON mandatory:

public class ChildJSON{
    private String childName;
    private String childType;
}

If I directly add @NotNull to my ChildJSON fields then it would throw error if type is not present in JSON.

Here is my client file which will read the JSONFILE:

public class Client {
    public static void main(String args[]) {
        final ObjectMapper objectMapper = new ObjectMapper();
        ParentJSON json = objectMapper.readValue(ApplicationMain.class.getResourceAsStream("/JSONFile.json"), ParentJSON.class);
    }
}

My json would look something like this:

{
    {
      "name":"Hello"
    },
    {
      "name":"Bye",
      "type":{
        "childName":"childByeName",
        "childType":"childByeType"
      }
    }
}

Upvotes: 0

Views: 1062

Answers (1)

Kyle Millar
Kyle Millar

Reputation: 246

The type field will not be mandatory if your Parent class looks like this:

public class ParentJSON{
    @NotNull
    private String name;
    @Valid
    private ChildJSON type;
}

The @Valid annotation is required for the ChildJSON constraints to be evaluated. Then, you can add @NotNull to your Child class fields:

public class ChildJSON{
    @NotNull
    private String childName;
    @NotNull
    private String childType;
}

The ChildJSON fields will only be required if the type field is not null in the ParentJSON class.

Also, you will need to update your object mapper to only serialize non-null fields if you want your JSON to look exactly like that.

final ObjectMapper objectMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);

Note: Make sure you are providing two constructors for the ParentJSON class - one with the type field and one without it

Upvotes: 1

Related Questions