0

I am using one web service in my app. Unfortunately I am not expecting the response to be auto sorted based on the keys. I need the original response as it is in web. Can anyone let me know how to do this in iOS app.I am using the following code to show the response.

NSDictionary *response  = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

1 Answer 1

2

JSON objects have unordered keys. iOS is not sorting the keys in the data structure. It's just sorting them when you print out the result (for convenience). Internal to the data structure, there is no guaranteed order. It depends on how things hash.

There is no way to use NSJSONSerialization to create an "ordered dictionary" since ordered dictionaries don't exist in JSON. The way you fix this is to use a list of dictionaries, such as:

[ { "First": "A" }, { "Second", "B" } ]

This is promised to stay in order because it's a list.

If you can't change the format, and the format relies on order, then it's not proper JSON and you'll have to parse it some other way. Typically I try to do simple string parsing (splitting on newlines for instance) to find large valid JSON "chunks" that can be handed to the parser.

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

3 Comments

Thanks Rob. I really appreciate your reply for this.I am also trying to get a altrnative parser for this to achieve.
I don't know of any parser on iOS that will do this. It would have to return a non-standard type (i.e. it couldn't use a regular NSDictionary). "Ordered JSON objects" breaks the basic promises of JSON. If you could find a streaming parser (like SAX for XML), you could use that to get what you want, but I'm not aware of any streaming JSON parsers on iOS. It's what you'd look for, though.
Ah, YAJL may work that way: github.com/gabriel/yajl-objc See YAJLParser specifically.

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.