我是RestTemplate的新手,所以我正在寻求有关创建域类的帮助,该类将使用RestTemplate获得响应。我调用该网址的JSON结构如下所示:
[{
"id": "2",
"name": {
"firstname": "John",
"lastname": "Smith"
},
"address": {
"street": "123 Main St",
"city": "Perth",
"state": "GA"
}
},
{
"child": {
"info": {
"firstname": "Bob",
"age": "12"
}
}
},
{
"child": {
"info": {
"firstname": "Jessica",
"age": "22"
}
}
},
{
"child": {
"info": {
"firstname": "Robert",
"age": "9"
}
}
},
{
"child": {
"info": {
"firstname": "Beth",
"age": "9"
}
}
}
]
我知道我需要创建类来处理结构 我为第一部分{}
创建了一个类
class FirstPart {
private String id;
private String name;
private String address;
}
然后其他部分重复(结构相同,我可以得到0,1或更多{})。如何创建我的结构以获取响应?我相信我需要一个包含所有结构的类(我将其称为Principal)
所以我的帖子将包括url,正文和Principal.class
.....
RestTemplate restTemplate = new RestTemplate();
Principal principal;
principal= restTemplate.postForObject(url,requestBody,Principal.class);
return principal
谢谢!
答案 0 :(得分:0)
执行以下操作,并在JSON中进行少量修改:
public class InfoDto{
private String firstname;
private Integer age;
//getters & setters
}
public class ChildDto{
private InfoDto info;
//getters & setters
}
public class AddressDto{
private String street;
private String city;
private String state;
//getters & setters
}
public class UserDetails{
private String firstname;
private String lastname;
//getters & setters
}
public class RestResponseDto{
private Long id;
private UserDetails name;
private AddressDto address;
private List<ChildDto> childs;
//getters & setters
}
JSON
[{
"id": "2",
"name": {
"firstname": "John",
"lastname": "Smith"
},
"address": {
"street": "123 Main St",
"city": "Perth",
"state": "GA"
}
},
childs:[{
"child": {
"info": {
"firstname": "Bob",
"age": "12"
}
}
},
...............
.............
...................
]
]
RestTemplate restTemplate = new RestTemplate();
RestResponseDto principal;
principal= restTemplate.postForObject(url,requestBody,RestResponseDto.class);
return principal