wei
wei

Reputation: 4727

JSON Sort String

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!

Upvotes: 0

Views: 422

Answers (1)

Codo
Codo

Reputation: 78815

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.

Upvotes: 1

Related Questions