0

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

user3409650
  • 505
  • 3
  • 12
  • 25
  • 1
    possible duplicate of [How to parse JSON in Java](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) –  Aug 05 '14 at 11:23
  • 1
    Are you sure, that the response looks exactly like you posted it? It is not valid JSON. –  Aug 05 '14 at 11:24
  • @Tichodroma: I trimmed the original returned Json because it was too big. but it is a valid JSon, so I should trim "rd" variable which is a json? – user3409650 Aug 05 '14 at 11:31
  • No, it is not valid JSON. Please test it at http://jsonlint.com/ –  Aug 05 '14 at 11:33

3 Answers3

1

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

FreakyBytes
  • 151
  • 1
  • 9
0

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, e.g.

mapper.readTree(responseText).get("foo").get("bar")
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

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));
} 
}
Ritesh Gune
  • 16,629
  • 6
  • 44
  • 72