1

I have the following json returned to me from an API.

"sections": {
  "1": {
    "title":"Within 1 Km",
    "count":6
  },
  "3": {
    "title":"Within 3 Km",
    "count":1
  },
  ....and some more here

It's worth nothing this is not a JSON Array.

I need to iterate through the objects contained with sections, but because it is not a JSON array, I'm extracting the names ("1", "3", and so on) and looping through the JSON selecting each object.

JSONObject jsSecs = new JSONObject(data).getJSONObject("sections");
JSONArray jsSecsArray = jsSecs.names();

What I've noticed is that JSONArray.names() will return an array of names out of order from the JSON.

I expected 0th element to contain "1", 1st element to contain "3".

What I got was 0th element to contain "10", 2nd element to contain "1", etc - all out of sync.

What's going on here? Have I missed something obvious? I don't want to reorder things if I don't have to. It seems like more fuss than it's worth.

2
  • show us the name function plz Commented Mar 30, 2012 at 11:58
  • Just a side note: Use jakson json, and your problem is solved in one liner. Commented Mar 30, 2012 at 12:05

1 Answer 1

4

check http://www.json.org/javadoc/org/json/JSONObject.html, it clearly explains:

A JSONObject is an unordered collection of name/value pairs.

Means A JSONObject does not maintain order of insertion. as lists or JSONArray has.

Sign up to request clarification or add additional context in comments.

1 Comment

Well that explains it. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.