-1

I want to display all data in Key value pair in a below JSON String.

response {
community: “worker”
communitystr: "<null>";
workspace: abs;
email: "<null>";
admin: false;
persona: "<null>";
userinfo: {
   info: {
    contact1: {
        firstname: “jon”;
        lastname: “Doe”
        phone: “9885678905”;

        objectname: contact;
        id: 9;
    };
    event1: {
        eventname: “party”;
        description: "";
        order: 6;
        id: 4;
        objectname: events;
    };
    files: {
        filename: “sample”;
        description: "";
        order: 11;
        id: 11;
        objectname: files;

    };
  };
};

As I am new to this finding difficulty. how to get the key value in array or any other accessible format ? thanks for any help

1 Answers1

2

First your json format is not correct, if you try to use JSONObject or GSON library is will throw not json type exception.

Please use a correct format of json something like this.

{
    [
        {
           username: "somename",
           userId : "1"
        },
        {
           username: "somename2",
           userId: "2"
        }
    ]
}

General JSONObject contain JSONArray or JSONObject which you can parse it using android built in JSON.

JSONArray jsonArray = new JSONArray(yourJSONArray);
for(int i = 0; i < jsonArray.length(); i++){
   JSONObject json = jsonArray.getJSONObject(i);
   String username = json.getString("username"); //here is how to get username key
}

Here is how you loop through every key and value inside your JSON object

JSONArray array = new JSONObject(result);
    Iterator<String> iter = jsonObject.keys();
    while (iter.hasNext()) {
        String key = iter.next();
        String value = jsonObject.getString(key)
        Log.d(TAG,"key = "+key+" value = "+value); // always use tag in log cat for preventing confusion
    }

Regardless anything you still need to have a proper format of JSON.

teck wei
  • 1,375
  • 11
  • 22