Reputation:
Hi I am using retrofit to send and receive data from server.How to parse if the keys are different.
Can any one help me how to parse json with below keys.
{"users": {"19x1": "Admin","19x5": "Manager"}}
Upvotes: 0
Views: 435
Reputation: 2814
Your json
structure is not correct. Basically you are having an array of users but you return object that has two fields 19x1
and 19x2
.
It's not possible to use Retrofit
and Gson
to parse a dynamic key
response. The only way to do is to use Plain Json
Parsing in Android. but you will need to know where is the data in the list so you can do something like.
jsonArray.getObject(index)
if you want to get a list of objects then change your json
to this structure
"users": [
{
"role_id": "19x1",
"description": "Admin"
},
{
"role_id": "19x5",
"description": "Manager"
}
]
Upvotes: 0
Reputation: 2115
The keys are not the problem the user should be an object
{
"users": {
"19x1": "Admin",
"19x5": "Manager"
}
}
Try the above code in any json validator to check.. ie https://jsonlint.com/
Updated to access the values:
<!DOCTYPE html>
<html>
<body>
<p>How to access nested JSON objects.</p>
<p id="demo"></p>
<script>
var myObj = {
"users": {
"19x1": "Admin",
"19x5": "Manager"
}
}
document.getElementById("demo").innerHTML += myObj.users["19x1"];
</script>
</body>
</html>
and for Android:
JSONObject jsonString = {"users": {"19x1": "Admin","19x5": "Manager"}};
JSONObject obj1 = new JSONObject(jsonString);
JSONObject obj2=obj1.getJSONObject("users");
JSONObject obj3=obj2.getJSONObject("19x1");
System.out.println("The value is " + obj3);
Upvotes: 1
Reputation: 86
The json you gave is not correct.It should be like this:
{"users": {"19x1": "Admin","19x5": "Manager"}}
You can check the accuracy of json object in here: https://www.bejson.com/
Upvotes: 0