简体   繁体   中英

How to get part of httpResponse in java

I want to get just ID from httpResponse after I did HttpGet.

This is my code:

HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://localhost:80/api/");

HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println(httpResponse);
BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));

String line = "";
while ((line = rd.readLine()) != null) {
  System.out.println(line);
}

which returns this:

{"list":[{"timestamp":{"$date":"2014-08-01T08:37:54.058Z"},"nameGroup":false,"_id":{"$oid":"53db5045ccf2b2399e0e6128"},"created":{"$date":"2014-08-01T08:31:01.139Z"}],"name":"John"}]}

But I just want Oid not the whole thing. Any idea?

Thanks

Strint you've got is json encoded data, so you need to decode it and than you are able to access the field "oid". There are several libaries around to acomplish this job:

  • gson
  • JsonSimple
  • Jackson etc.

My favorite for small projects is gson

Using Jackson or Gson , you can parse the response JSON and get exactly the part you need.

If you don't need the whole result, then there is no point in creating a reference object, just manually traverse the json document, eg

mapper.readTree(responseText).get("foo").get("bar")

I think instead of using a library just to get value of one parameter is not appropriate if you have other options available. I would suggest you to parse the json on yor own using the APIs provided. You can try following:

try {

JSONObject obj = new JSONObject(your_json_string);
String value= null; 

if (obj != null && obj.has(YOUR_KEY_FOR_PARAM)) {
                value = obj.getString(YOUR_KEY_FOR_PARAM));
} 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM