Getting Json object inside a Json object in Java

java, json

Solution

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

Problem

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!

Original source