Home > Software design >  Nested Json Object Returns Null When Converting to POJO
Nested Json Object Returns Null When Converting to POJO

Time:12-13

I have the below json that I'm trying to read into a JSON node and then map to a Java POJO object.

{
  "operation": "myoperation",
  "input": {
    "environment": "myEnv",
    "stage": "beta"
  }
}

Below is the POJO class

@JsonIgnoreProperties(ignoreUnknown = true)
public class Input {
    private String environment;
    private String stage;

    public String getEnvironment() {
        return apolloEnvironment;
    }

    public String getStage() {
        return stage;
    }
}

When I read the above tree using the mapping below, I get null for the environment and stage properties.

Input myInput = OBJECT_MAPPER.treeToValue(inputJson, Input.class);
System.out.println(myInput.getEnvironment()); //returns null
System.out.println(myInput.getStage()); //returns null

I would like to read the environment and stage property values, how can I do this with the above logic? Thanks in advance.

CodePudding user response:

The Input object in your JSON is wrapped by another object. So instead of trying to parse the whole Tree as Input, you need to obtain the Value mapped to the property input and then parse it.

Note that setters should be in place in your Input class.

String jsonString = """
    {
      "operation": "myoperation",
      "input": {
        "environment": "myEnv",
        "stage": "beta"
      }
    }
    """;

ObjectMapper mapper = new ObjectMapper();        
JsonNode node = mapper.readTree(jsonString).get("input");
    
Input myInput = mapper.treeToValue(node, Input.class);
System.out.println(myInput.getEnvironment());
System.out.println(myInput.getStage());

Output:

myEnv
beta

Another option would be to declare another class, wrapping Input, let's say InputWrapper. The would allow to deserialize the JSON you directly into the InputWrapper instance and then access nested Input via getter method.

Here's how such wrapper class might look like (Lombok's annotations used for brevity):

@Setter
@Getter
public static class InputWrapper {
    private String operation;
    private Input input;
}

@Setter
@Getter
public static class Input {
    private String environment;
    private String stage;
}

Parsing logic:

String jsonString = """
    {
      "operation": "myoperation",
      "input": {
        "environment": "myEnv",
        "stage": "beta"
      }
    }
    """;

ObjectMapper mapper = new ObjectMapper();        

InputWrapper inputWrapper = mapper.readValue(jsonString, InputWrapper.class);
Input myInput = inputWrapper.getInput();
        
System.out.println(myInput.getEnvironment());
System.out.println(myInput.getStage());

Output:

myEnv
beta
  • Related