如何从RestTemplate交换方法中获取特定对象?

时间:2016-08-10 07:05:05

标签: java json spring rest web

我有一个终点让我回答这个问题:

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

2 个答案:

答案 0 :(得分:2)

使用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仅提取您感兴趣的数据。

答案 1 :(得分:2)

您可以使用simple-json.jarJSONObject

中提取该对象

可下载的Jar Link - simple-json.jar Download Link

Maven Jar导入Maven Repository pom syntax

你的实际对象是

  {
  "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
      }
    }
  }
} // hold this complete object in any string reference Variable.
  

这里我假设String jsonString保存完整的json对象,如上所述。

import org.json.simple.parser.JSONParser; 
import org.json.simple.parser.JSONObject;

// implemetation logic for extracting jsonObject.

private JSONObject extractFirstBlock(String jsonString) throws ......{

   JSONObject jsonObj ;

   JSONParser parser=new JSONParser();  // parser to parse string to JSONObject
   jsonObj = (JSONObject) parser.parse(jsonString); // parse the Object using parse Method.
  String desiredObject = (String) jsonObj.get("body"); // this Object contains your desired output which you wish to receive.

   jsonObj = parser.parse(desiredObject);
   desiredObject = jsonObj.get("elems"); // you will get your desired object as you expected.
}

desiredObject中,您将获得期望值为JSONObject。

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