Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a value from deep inside JSON

Tags:

java

json

gson

I am connecting to a third party API and getting back a long JSON string. I only need one value from it, but it is located pretty deep inside the hierarchy. Is there a simple way to get it, without going through the whole thing? I looked all over but nothing seems easy.

Here's my example:

"response":{"status":1,"httpStatus":200,"data":{"myDesiredInfo":"someInfo"},"errors":[],"errorMessage":null}}

I've been trying to use Gson so I can get this blob as a JsonObject. I was sure there's something simple, like this:

jsonObject.get("myDesiredInfo") 

or at the minimum something like this:

jsonObject.get("response.data.myDesiredInfo") 

But it doesn't seem to exist.

So is there any parser out there that will allow me to do this?

like image 779
Eddy Avatar asked Dec 12 '25 13:12

Eddy


2 Answers

This is my json string

String s="{"age":0,"name":"name","email":"emailk","address":{"housename":"villa"}}";

I use following code to get housename

    JsonElement je = new JsonParser().parse(s);
    JsonObject asJsonObject = je.getAsJsonObject();
    JsonElement get = asJsonObject.get("address");
    System.out.println(s + "\n" + get);
    JsonObject asJsonObject1 = get.getAsJsonObject();
    JsonElement get1 = asJsonObject1.get("housename");
    System.out.println(get1);

The Following is my output :

{"age":0,"name":"name","email":"emailk","address":{"housename":"villa"}}
{"housename":"villa"}
"villa"

I don't think there is another way to do this. I also tried to do in other ways but i didn't get any output.

like image 118
Parvathy Avatar answered Dec 15 '25 08:12

Parvathy


The following way you can retrieve from your jsonObject.

JSONObject jObject = new JSONObject(yourresponse);
Log.i("Desired Info is ",jObject.getJSONObject("response").getJSONObject("data").getString("myDesiredInfo"));
like image 26
Harish Avatar answered Dec 15 '25 08:12

Harish