简体   繁体   中英

Spring Boot RestTemplate List

I get a response like this:

{  
   "data":[  
      {  
         "object1":"example",
         "object2":"example",
         "object3":"example",
         "object4":"example",
         "object5":"example"
      },
      {  
         "object1":"example",
         "object2":"example",
         "object3":"example"
      }
   ]
}

Now I wanted to Map this data to my class DTO but there I get an "error" because the DTO has no data field. I want it in a List or Array of my class. Like:

List<MyClass> list = restTemplate.getForObject(url, MyClass.class);

I hope you know what I mean?

One approach comes to mind is to convert the JSON response to a Map<String, List<MyClass>> and then query the map, ie map.get("data") , to get the actual List<MyClass> .

In order to convert the JSON response to Map<String, List<MyClass>> , you need to define a Type Reference :

ParameterizedTypeReference<Map<String, List<MyClass>>> typeRef = 
                           new ParameterizedTypeReference<Map<String, List<MyClass>>>() {};

Then pass that typeRef to the exchange method like the following:

ResponseEntity<Map<String, List<MyClass>>> response = 
                                 restTemplate.exchange(url, HttpMethod.GET, null, typeRef);

And finally:

System.out.println(response.getBody().get("data"));

If you're wondering why we need a type reference, consider reading Neal Gafter's post on Super Type Tokens .

Update : If you're going to deserialize the following schema:

{
    "data": [],
    "paging": {}
}

It's better to create a dumb container class like the following:

class JsonHolder {
    private List<MyClass> data;
    private Object paging; // You can use custom type too.

    // Getters and setters
}

Then use it in your RestTemplate calls:

JsonHolder response = restTemplate.getForObject(url, JsonHolder.class);
System.out.println(response.getData()); // prints a List<MyClass>
System.out.println(response.getPaging()); // prints an Object

You can use Spring's ResponseEntity and array of MyClass. Below code will return an array of MyClass wrapped around

For eg

ResponseEntity<MyClass[]> response = restTemplate.exchange(
   url,
   HttpMethod.GET,
   request,
   MyClass[].class
);
... 
// response null check etc. goes here
...
MyClass[] myArr = response.getBody();

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