我想使用spring boot构建一个请求方法:我必须使用restful api并将其转换为另一个rest端点。
我在www.exampleapiurl.com/details上有一个json回复
[{
"name": "age",
"value": "Child"
},
{
"name": "recommendable",
"value": true
},
{
"name": "supported",
"value": yes
},
]
[{
"name": "age",
"value": "Adult"
},
{
"name": "recommendable",
"value": true
},
{
"name": "supported",
"value": no
},
]
我希望回复是:
[{
"age": "Child"
},
{
"recommendable": true
},
{
"supported": "yes"
},
]
[{
"age": "Adult"
},
{
"recommendable": true
},
{
"supported": "no"
},
]
为此,我有一个带getter和setter的属性类: Attributes.class
@JsonIgnoreProperties(ignoreUnknown = true)
public class Attributes {
private String age;
private boolean recommendable;
private String supported;
getter and setter for these:
}
这是我的service.java类
@Service
public class CService {
private static RestTemplate restTemplate;
public String url;
@Autowired
public CService(String url) {
this.url = url;
}
public Attributes getAttributes() {
HttpHeaders headers= new HttpHeaders();
headers.add("Authorization", "some value");
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, Attributes.class);
return response.getBody();
}
}
这是我的controller.class
@Controller
public class CController {
private CService cService;
@Autowired
public CController(CService cService) {
this.cService = cService;
}
@RequestMapping(value="/example")
@ResponseBody
public Attributes getCAttributes() {
return cService.getAttributes(); }
}
授权成功但是, 我现在没有得到任何回复
答案 0 :(得分:0)
您可以做的是创建一个模型类,以便从示例API中恢复响应 如下。
@JsonIgnoreProperties(ignoreUnknown = true)
public class Details{
private String name;
private String value;
@JsonProperty("value")
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@JsonProperty("name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
然后按如下所示更改调用RestTemplate代码
Details[] details = null;
//Keeps the example API's data in array.
ResponseEntity<Details[]> response = restTemplate.exchange(url, HttpMethod.GET, request, Details[].class);
details = response.getBody();
//下一步是处理此数组并将响应发送回您的客户端
List<Attributes> attributes = new ArrayList<Attributes>();
Attributes attr = null;
for(Details detail : details) {
attr = new Attributes();
//set the values here
}
//returns the attributes here
attributes.toArray(new Attributes[attributes.size()]);