在使用[NSJSONSerialization dataWithJSONObject:]转换为NSData时保留NSDictionary键的顺序 [英] Keeping the order of NSDictionary keys when converted to NSData with [NSJSONSerialization dataWithJSONObject:]

查看:724
本文介绍了在使用[NSJSONSerialization dataWithJSONObject:]转换为NSData时保留NSDictionary键的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

  NSDictionary * params = @ {
@Checkout:@
@conditions:@ {@Checkout.user_id:@ 1},
@order:@ {@Checkout.id:@DESC}
} ,
@PaymentState:@ [],
@Offer:@ []
};

此字典包含通过webservice URL传递JSON字符串的Web服务请求的参数。我得到JSON字符串使用NSJSONSerialization类,像这样:

  NSData * jsonData = [NSJSONSerialization dataWithJSONObject:params options:零]; 
NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

问题是:jsonStringkeys的顺序与原始params字典键顺序不同, :

  {
Offer:[],
PaymentState:[],
Checkout:{
conditions:{Checkout.user_id:6},
order:{Checkout.id:DESC}
}

}



也就是说,PaymentState 和Offer键先在jsonString,我需要维护
原来的顺序。这很重要,像这样:

  {
Checkout:{
conditions: {Checkout.user_id:6},
order:{Checkout.id:DESC}
},
Offer:[],
PaymentState:[]

}



我使用

基本上, OrderedDictionary 包含 NSMutableDictionary NSMutableArray 键,以跟踪键的顺序。它实现了子类化 NSDictionary / NSMutableDictionary 所需的方法,只是将方法调用传递到内部 NSMutableDictionary


I have the following situation:

NSDictionary *params = @{
    @"Checkout" : @{
        @"conditions" : @{@"Checkout.user_id" : @1},
        @"order" : @{@"Checkout.id" : @"DESC"}
    },
    @"PaymentState" : @[],
    @"Offer" : @[]
};

This dictionary contains params for a webservice request passing a JSON string with the webservice URL. I get the JSON string using NSJSONSerialization class, like this:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

The problem is: jsonString "keys" is ordered differently from the original params dictionary keys order, like this:

{
"Offer":[],
"PaymentState":[],
"Checkout":{
    "conditions":{"Checkout.user_id":6},
    "order":{"Checkout.id":"DESC"}
}

}

That is, the "PaymentState" and "Offer" keys come first in jsonString, and i need maintain the original order. This is very important, like this:

{
"Checkout":{
    "conditions":{"Checkout.user_id":6},
    "order":{"Checkout.id":"DESC"}
},
"Offer":[],
"PaymentState":[]

}

So guys, how can i do that??

解决方案

I use OrderedDictionary from CocoaWithLove whenever I need to keep the order of my dictionary keys.

Basically, OrderedDictionary contains an NSMutableDictionary and an NSMutableArray for the keys inside it, to keep track of the order of the keys. It implements the required methods for subclassing NSDictionary/NSMutableDictionary and just "passes" the method call to the internal NSMutableDictionary.

这篇关于在使用[NSJSONSerialization dataWithJSONObject:]转换为NSData时保留NSDictionary键的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆