简体   繁体   中英

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!

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM