0

framework. Hi I'm using json-framework.

How to get sorted string when using JSONRepresentation method? Here is my code:

NSMutableDictionary *tUserIDParam = [NSMutableDictionary dictionary];

[tUserIDParam setObject:@"UserID" forKey:@"@key"];
[tUserIDParam setObject:@"string" forKey:@"@type"];
[tUserIDParam setObject:@"mark" forKey:@"#text"];

NSMutableDictionary *tPasswordParam = [NSMutableDictionary dictionary];
[tPasswordParam setObject:@"Password" forKey:@"@key"];
[tPasswordParam setObject:@"string" forKey:@"@type"];
[tPasswordParam setObject:@"123456" forKey:@"#text"];

NSArray *tParams = [NSArray arrayWithObjects:tUserIDParam,tPasswordParam, nil];
NSDictionary *tParam = [NSDictionary dictionaryWithObject:tParams forKey:@"param"];

NSMutableDictionary *tRequests = [NSMutableDictionary dictionary];
[tRequests setObject:[NSNull null] forKey:@"key"];
[tRequests setObject:[NSNull null] forKey:@"basic"];
[tRequests setObject:tParam forKey:@"conditions"];

NSDictionary *tRequest = [NSDictionary dictionaryWithObject:tRequests forKey:@"request"];

NSString *tJSONStrFromDict = [tRequest JSONRepresentation];

I want to get JSON string like:

{"request":{"key":null,"basic":null,"conditions":{"param":[{"@key":"UserID","@type":"string","#text":"mark"},{"@key":"Password","@type":"string","#text":"123456"}]}}}

But I got this string from above code:

{"request":{"basic":null,"conditions": {"param":[{"#text":"mark","@key":"UserID","@type":"string"},{"#text":"123456","@key":"Password","@type":"string"}]},"key":null}}

I try to use SBJSONWriter sortKeys property,it does not work...

Have any way to solve my problem?

Thanks!

1 Answer 1

1

NSMutableDictionary instance do not preserve the order of elements, neither in alphabeticallz order nor in the order they were inserted. This is independent of JSON.

Furthermore, JSON's data model for object doesn't guarantee order either. If you want a certain order, you'll have to use JSON arrays for the ordered parts.

BTW.: The effect of SBJSONWriter sortKeys is to output the object elements (or properties) alphabetically sorted by the key name. This is what you get.

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

2 Comments

Hi Codo ~ Thanks for you reply. So if I want certain order , I should change my JSON format. Using NSMutableArray ,and add each object contain one NSDictionary(one pair key/value). Is only the way I can do?
If the order is relevant - and I don't know of the overall context to understand why this is so - then yes, an array of dictionaries is the easiest way to achieve this.

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.