JSON排序字符串

时间:2011-09-18 11:20:12

标签: iphone json sorting nsdictionary nsmutabledictionary

框架。 嗨,我正在使用json-framework。

使用JSONRepresentation方法时如何获取排序字符串? 这是我的代码:

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];

我想获得JSON字符串,如:

{ “请求”:{ “键”:NULL, “基本”:NULL, “条件”:{ “参数”:[{ “@键”: “用户ID”, “@类型”: “串”, “#text”: “标记”},{ “@键”: “密码”, “@类型”: “串”, “#文本”: “123456”}]}}}

但是我从上面的代码中得到了这个字符串:

{ “请求”:{ “基本”:NULL, “条件”: { “参数”:[{ “#文”: “标志”, “@键”: “用户名”, “@类型”: “串”},{ “#文”: “123456”, “@键”: “密码”, “@类型”: “串”}]}, “密钥”:空}}

我尝试使用SBJSONWriter sortKeys属性,但它不起作用...

有办法解决我的问题吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

NSMutableDictionary 实例不保留元素的顺序,既不按字母顺序也不按插入顺序保存。这与JSON无关。

此外,JSON的对象数据模型也不保证顺序。如果您需要某个订单,则必须为订购的零件使用JSON数组。

BTW。:SBJSONWriter sortKeys的效果是按键名称按字母顺序输出对象元素(或属性)。这就是你得到的。