如何从RestTemplate交换方法获取特定对象? [英] How to get specific object from RestTemplate exchange method?
本文介绍了如何从RestTemplate交换方法获取特定对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个端点,它向我返回此响应:
I have an end-point which returns me this response:
{
"head": {
"status": 200,
"ok": true,
"messages": [],
"errors": [],
"references": {}
},
"body": {
"id": "d57a9c7aef9842c2e31a0f49c",
"flowId": "f57979d06f9842c3e94f1f197",
"creationDate": 1470744494732,
"path": "/luafanti/test",
"version": 0,
"elems": {
"xxx": {
"type": "integer",
"value": 200
}
}
}
}
我的问题是,如何制作一个只能用我的json响应的一部分填充的模型.例如,使用此:
My question is, how to make a model that can be populated with only a part of my json response. For example, with this:
"xxx": {
"type": "integer",
"value": 200
}
或者这个:
"elems": {
"xxx": {
"type": "integer",
"value": 200
}
}
推荐答案
使用Jackson,您可以将模型定义如下:
Using Jackson, you can define your model as the following:
@JsonIgnoreProperties(ignoreUnknown=true)
public class MyResponseModel {
private Body body;
public void setBody(Body body) {this.body = body;}
public Body getBody() {return body;}
@JsonIgnoreProperties(ignoreUnknown=true)
public static class Body {
private Elems elems;
// getter and setter for elems
}
@JsonIgnoreProperties(ignoreUnknown=true)
public static class Elems {
private Xxx xxx;
// getter and setter for xxx
}
@JsonIgnoreProperties(ignoreUnknown=true)
public static class Xxx {
private String type;
private String value;
// getter and setter for type and value
}
}
以上内容非常冗长,特别是如果您仅对响应的一小部分感兴趣时.将响应作为字符串处理然后使用例如 JsonPath 仅提取您感兴趣的数据.
The above is quite verbose, particularly if you are only interested in a very small part of the response. It may be more practical to handle the response as a String and then use e.g. JsonPath to extract only the data you are interested in.
这篇关于如何从RestTemplate交换方法获取特定对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文