简体   繁体   中英

Nested Json Object Returns Null When Converting to POJO

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM