简体   繁体   中英

Deserializing JSON response to Java using RestTemplate and Jackson

I'm running into some headaches with deserializing JSON into Java objects in a Spring Boot 1.5 app with Jackson.

As you can see below, the JSON response is an array consisting of a single JSON object with some nested attributes:

[
  {
    "deploymentProject": {
        "id": 57966596,
        "name": "MyApp 6.3"
    },
    "environmentStatuses": [{
            "environment": {
                "id": 57245736,
                "name": "Dev1",
                "deploymentProjectId": 57966596
            },
            "deploymentResult": {
                "deploymentVersionName": "App-51",
                "id": 59769040
            }
        },
        {
            "environment": {
                "id": 57245737,
                "name": "Dev2",
                "deploymentProjectId": 57966596
            },
            "deploymentResult": {
                "deploymentVersionName": "App-51",
                "id": 59769041
            }
        }
    ]
  }
]

ResultData.java

I don't care about the deploymentProject attribute so I'm only including the environmentStatuses in ResultData .

@JsonIgnoreProperties(ignoreUnknown = true)
public class ResultData {   
  private EnvironmentStatus[] environmentStatuses;

  // Getters and setters omitted
}

EnvironmentStatus.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class EnvironmentStatus {

    private Environment environment;
    private DeploymentResult deployment;

    // Getters and setters omitted
}

Environment.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class Environment {
    private long id;
    private String name;
    private String deploymentProjectId;
    //Getters and setters omitted
}

DeploymentResult.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class DeploymentResult {
    private long id;
    private String deploymentVersionName;
    // Getters and setters omitted
}

When I make the call to RestTemplate in my service class, the environmentStatuses array is null :

Service.java

ResponseEntity<List<ResultData>> response = restTemplate.exchange(uriBuilder.toUriString(),
                HttpMethod.GET, null, new ParameterizedTypeReference<List<ResultData>>() {});

return response.getBody();

private DeploymentResult deployment; is the next issue.. If you want this name in your code you need to annotate with the json structure name. or if not name it deploymentResult

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