Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Json object inside a Json object in Java

Tags:

java

json

So I have some code that is able to send this out:

  {"id":1,
   "method":"addWaypoint",
   "jsonrpc":"2.0",
   "params":[
     {
       "lon":2,
       "name":"name",
       "lat":1,
       "ele":3
     }
    ]
   }

The server receives this JSON object as a string named "clientstring":

 JSONObject obj = new JSONObject(clientstring); //Make string a JSONObject
 String method = obj.getString("method"); //Pulls out the corresponding method

Now, I want to be able to get the "params" value of {"lon":2,"name":"name","lat":1,"ele":3} just like how I got the "method". however both of these have given me exceptions:

String params = obj.getString("params");

and

 JSONObject params = obj.getJSONObject("params");

I'm really at a loss how I can store and use {"lon":2,"name":"name","lat":1,"ele":3} without getting an exception, it's legal JSON yet it can't be stored as an JSONObject? I dont understand.

Any help is VERY appreciated, thanks!

like image 759
Exception Avatar asked Jan 17 '26 14:01

Exception


2 Answers

params in your case is not a JSONObject, but it is a JSONArray.

So all you need to do is first fetch the JSONArray and then fetch the first element of that array as the JSONObject.

JSONObject obj = new JSONObject(clientstring); 
JSONArray params = obj.getJsonArray("params");
JSONObject param1 = params.getJsonObject(0);
like image 148
Lokesh Avatar answered Jan 20 '26 02:01

Lokesh


How try like that

    JSONObject obj = new JSONObject(clientstring);
    JSONArray paramsArr = obj.getJSONArray("params");


    JSONObject param1 = paramsArr.getJSONObject(0);

    //now get required values by key
    System.out.println(param1.getInt("lon"));
    System.out.println(param1.getString("name"));
    System.out.println(param1.getInt("lat"));
    System.out.println(param1.getInt("ele"));
like image 42
Wundwin Born Avatar answered Jan 20 '26 03:01

Wundwin Born



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!