Exception
Exception

Reputation: 307

Getting Json object inside a Json object in Java

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!

Upvotes: 3

Views: 37648

Answers (3)

incr3dible noob
incr3dible noob

Reputation: 441

Here "params" is not an object but an array. So you have to parse using:

JSONArray jsondata = obj.getJSONArray("params");

for (int j = 0; j < jsondata.length(); j++) {
    JSONObject obj1 = jsondata.getJSONObject(j);
    String longitude = obj1.getString("lon");
    String name = obj1.getString("name");
    String latitude = obj1.getString("lat");
    String element = obj1.getString("ele");
  }

Upvotes: 1

Wundwin Born
Wundwin Born

Reputation: 3475

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"));

Upvotes: 2

Lokesh
Lokesh

Reputation: 582

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);

Upvotes: 3

Related Questions