luafanti luafanti - 4 months ago 15
reST (reStructuredText) Question

How to get specific object from RestTemplate exchange method?

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
}
}
}
}


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
}


or this:

"elems": {
"xxx": {
"type": "integer",
"value": 200
}
}

Answer

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 
  }
}

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.