Spring RestTemplate将JSON响应中的特定键值映射到POJO类

时间:2017-11-24 15:11:03

标签: java json spring resttemplate objectmapper

我有一个API,它以这种格式返回JSON:

 {
      "errors": null,
      "someKey1": "someValue1",
      "someKey2": "someValue2",
      "response": {
          "id": 21,
          "key1": "value1",
          "key2": "value2",
          "key3": "value3",
          "key4": {
              "key5": [
                  {
                      "ABC": "abc",
                      "XYZ": 1,
                      "PQR": "pqr"
                  },
                  {
                      "ABC": "abc",
                      "XYZ": 3,
                      "PQR": "pqr"
                  }
              ]
          },
          "key6": "value6"
      }
    }

我还有一个POJO类,其字段对应于JSON响应的response键,因为someKey1someKey2errors键与我的相关用例。

是否可以将JSON响应映射到我的Java POJO类,即仅映射response键内的值?

一种可能的方法是接受String响应并使用setter方法将其映射到我的POJO。

String apiResponse = restTemplate.exchange(someUrl, HttpMethod.GET, new HttpEntity<>(authHeader), String.class).getBody();
JSONObject jsonObject = new JSONObject(apiResponse);
MyObject myObject = buildNewObject(jsonObject.get("response"));

有没有更好的方法。像这样的东西? :

ResponseEntity<MyObject> responseEntity = restTemplate.exchange(someUrl, HttpMethod.GET, new HttpEntity<>(authHeader), MyObject.class).getBody().get("response");

2 个答案:

答案 0 :(得分:0)

您可以使用RestTemplate的getForObject。

代码示例:

HttpClient client = new HttpClient();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("USERNAME","PASS");
RestTemplate template = new RestTemplate(commons);
MyObject myObject = template.getForObject(someUrl,MyObject.class);

public class MyObject  {
    @JsonProperty(value="response")
    private Map<String,String> response;
}

答案 1 :(得分:0)

您可以创建一个Mapper类,将POJO作为一个对象,将其他额外值作为变量创建,如下所示

class Mapper{

private PojoClass response;
private String someKey1;
private String somekey2;
private String errors;

//Create getters and setters

}

现在response将自动绑定到POJO,其他值将绑定到相应的key1 key2和错误