Getting Json object inside Json object in Java
So, I have some code capable of sending this message:
{"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 get the value "params" {"lon": 2, "name": "name", "lat": 1, "ele": 3} just like I got the method ". However both of them gave 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, this is legal JSON, but it doesn't can be saved as JSONObject? I do not understand.
Any help is VERY appreciated, thanks!
source to share
params
in your case, not a JSONObject , but it's a JSONArray .
So all you have to do is first get JSONArray
and then extract the first element of this array as JSONObject
.
JSONObject obj = new JSONObject(clientstring);
JSONArray params = obj.getJsonArray("params");
JSONObject param1 = params.getJsonObject(0);
source to share
How to do it
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"));
source to share
Here "params" is not an object, but an array. Therefore, you need to analyze the usage:
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");
}
source to share