英文:
How to convert a JsonObject object to a list of another object type
问题
我有一个将返回类似以下内容的对象列表的服务:
{
"myobject": [
{
"first": "10",
"second": 5.000
},
{
"first": "20",
"second": 20.000
},
{
"first": "30",
"second": 50.000
}
]
}
我使用以下请求获取此对象:
public String getMyObject() {
String url = UriComponentsBuilder.fromHttpUrl(myUrl);
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
return response.getBody();
}
我需要将此列表放入此类型的对象列表中:
@Getter
@Setter
public class MyObject {
private String firstParam;
private String secondParam;
}
如何实现?有人可以帮助我吗?
英文:
I have a service that will return a list of objects something like this:
{
"myobject": [
{
"first" : "10",
"second": 5.000
},
{
"first" : "20",
"second": 20.000
},
{
"first" : "30",
"second": 50.000
}
]
}
I take this object with this request
public String getMyObject() {
String url = UriComponentsBuilder.fromHttpUrl(myUrl);
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
return response.getBody();
}
I need to put this list inside a list of Objects of this type:
@Getter
@Setter
public class MyObject{
private String firstParam
private String secondParam
}
How to do this? Can anybody help me?
答案1
得分: 0
这里的主要问题是您在这行代码中期望的响应对象是什么:
ResponseEntity<myObject[]> response = restTemplate.getForEntity(url , myObject[].class);
相反,您应该请求一个 MyDTO 对象,因为您的控制器也在返回一个 MyDTO 对象:
ResponseEntity<MyDTO> response = restTemplate.getForEntity(url , MyDTO.class);
然后通过从 ResponseEntity 响应对象中提取 MyDTO 对象,在提取 MyDTO
对象后使用以下代码来检索列表:
List<MyObject> myList = myDTO.getMyObject();
英文:
The main problem here is what you expect as a response object at this line:
ResponseEntity<myObject[]> response = restTemplate.getForEntity(url , myObject[].class);
Instead you should ask for a MyDTO object since also your controller is returning a MyDTO object:
ResponseEntity<MyDTO> response = restTemplate.getForEntity(url , MyDTO.class);
and retrieving the list with a
List<MyObject> myList = myDTO.getMyObject();
after extracting the MyDTO
object from the ResponseEntity
response object.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论