3

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!

2
  • 1
    I have never used JSONObject in java.. I used play-json, but it seems like params is an array because of the [. Can you try JSONArray - params = obj.getJSONArray("params") Commented Dec 4, 2014 at 4:06
  • Thanks, I just realized that this was the problem this whole time, such a minor thing to overlook! Thanks Commented Dec 4, 2014 at 4:08

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@Exception have a look at this, might help you
2

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.