0

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

3 Answers3

1

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);
norcal johnny
  • 2,050
  • 2
  • 13
  • 17
0

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"
    }
]
AouledIssa
  • 2,528
  • 2
  • 22
  • 39
0

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/

Henry
  • 86
  • 2
  • Not a correct!! Gson doesn't work in this fashion. You need to know the parse model to be able to parse. Otherwise you will just have to parse using plain using plain java json parsing – AouledIssa Jun 02 '20 at 14:13