我有一个端点可以返回以下响应:
{
"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响应的一部分填充的模型。例如,与此:
"xxx": {
"type": "integer",
"value": 200
}
或这个:
"elems": {
"xxx": {
"type": "integer",
"value": 200
}
}
最佳答案
使用Jackson,您可以将模型定义如下:
@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仅提取您感兴趣的数据。
关于java - 如何从RestTemplate交换方法获取特定对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38866411/