1

How do I parse this object and get the name (key) for each person?

I can't just do String name = jsonObject.getString("name"); because the name is the key, not the value.

JSONObject jsonObject =

{
    "data" :
    [{
        "Bob": {
            "last-name": "Jorgenson",
            "email": "b@b.com",
        },

        "Steve": {
            "last-name": "Bobson",
            "email": "steve@juno.com",
        },
    }],
    "statusCode" : 200
}

So what's the best way to parse it with the dynamically-named keys?

Update:

jArray was taken from the jsonObject which is now represented. However, I was having trouble implementing answers because of type errors related to trying to get jArray from jsonObject.get("data")

Disclaimer

Yes, this is pretty basic stuff. The dynamic bit is throwing me off though. There are many similar questions, but they usual involve a number of other factors. I can successfully download the data and store it in the JSONObject jsonObject above. I just need to figure out how to parse the data as outlined above.

mrgnw
  • 1,771
  • 2
  • 17
  • 19

3 Answers3

5
    Iterator<String> keys = jsonObject.keys();
    while (keys.hasNext()) {
        String key = keys.next();
    }
JRomero
  • 4,878
  • 1
  • 27
  • 49
  • Beautifully succinct answer. Does the iterator skip item[0] because it starts with keys.next()? When I log key at each part of the while loop, it only Logs n-1 of the elements in the data (indicating it may be skipping an item at the beginning or the end.) – mrgnw Jul 11 '14 at 01:32
  • That's odd. Iterators always starts *before* the first item. Maybe you should post that as a new question... – JRomero Jul 11 '14 at 13:06
  • I'll double check and make sure I didn't mess anything up. Thanks! – mrgnw Jul 11 '14 at 19:25
2

The keys() method of JSONObject might be the method you're looking for.

Michael Barz
  • 276
  • 2
  • 11
0

you can use this:

for(int i=0;i<jsonArray.length();i++){
    JSONObject temp = jsonArray.getJSONObject(i);
    String name;
    Iterator<String> keys = temp.keys();
    if(keys.hasNext())
        name = keys.next();
}
SMR
  • 6,628
  • 2
  • 35
  • 56