Reputation: 205
Hi I want to parse this json:
[{
"codError": 0,
"msg": "OK"
}, {
"id": 1,
"role": {
"id": 4,
"name": "Super",
"description": "Roling.",
"rights": [],
"superuser": true,
"active": true,
"optimisticLock": 0
},
"now": null,
"points": [],
"firstName": null,
"lastName": null,
"loginName": "admin",
"password": null,
"connected": true,
"active": true,
"optimisticLock": null
},
["U4"]
]
I want to get role id that is 4, the loginName that is admin and the value of the array U4.
Here is how I am trying to do the parse:
// Role node is JSON Object
JSONObject role = getJSONObject(TAG_ROLE);
String role_id = role.getInt(TAG_ROLE_ID);
String loginName = getJSONObject(TAG_LOGINNAME);
how can I get U4 value? Thank you very much
Upvotes: 0
Views: 69
Reputation: 26034
Why should we do parsing of JSON if you are provided a ready made tool to parse a JSON and give you a complete hierarchy of Java classes???
Right??
Take a look at JsonSchema 2 Pojo site.
Provide your JSON input/output there. Select appropriate options like
Source type: JSON
Annotation style: GSON
Enable following 3 options
Select Jar button and you are done with.
Please validate your JSON first.
Upvotes: 0
Reputation: 1093
First of all, the U4 doesn't seems JSON correct. I would have write it like:
{
"your array":["U4"]
}
then use the method to get your array
JSONArray array = jsonObj.getJSONArray("your array");
then you can access the values on your JSONArray by iterating over it, like that
for (int i = 0; i < array.length(); i++) {
array.getJSONObject(i);
}
Hope I help
Upvotes: 1
Reputation: 23638
Try out as below:
JSONArray arry=new JSONArray("yourjsonstring");
for(int i=0;i<arry.length();i++)
{
JSONObject obj=arry.getJSONObject(i);
String role=obj.getString("role");
JSONObject obj2=new JSONObject(role);
String id=obj2.getString("id");
JSONArray array =obj.getJSONArray("U4");
}
Hope this helps you.
Upvotes: 0
Reputation: 12042
{
represents the Jsonobject and [
represents the jsonarray
Parse like this to get the role_id
loginName
from your json
JSONArray jsonarr =new JSONArray(yourstring);
JSONObject jobj=jsonarr.getJSONObject(1);
JSONObject role =jobj.getJSONObject("role");
String role_id = role.getInt("id");
String loginName=jsonarr.getString("loginName");
Upvotes: 1