How to retain order of JSON data retrieved with AFNetworking?

一世执手 提交于 2020-06-12 07:44:15

问题


I am using AFNetworking to retrieve JSON data from a web service. Part of the response string I get is:

{"DATA":{"LEASE TYPE":"3 Yrs + 0 renew of 0 Yrs","LANDLORD":"","TENANT":"test comp"... 

and so on. The order of the key values in the "DATA" dictionary ("LEASE TYPE","LANDLORD","TENANT"...) is important for presentation purposes. However, when AFNetworking calls NSJSONSerialization's:

+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;

method, the returned dictionary has the keys in a different order.

I notice that the AFJSONRequestOperation object has the server's response stored as an NSString, with everything in the correct order. However I'm not keen on parsing the JSON by hand if I can avoid it.

Can anyone suggest a way that will let me get at / keep the keys in their original order?

Thanks.


回答1:


If the order is important use an array not a dictionary, dictionaries are be by their nature unordered. Or add an array of dictionary keys in the order desired.

If you have no control over the response that is sent you will have to parse the JSON yourself at least for the ordering.




回答2:


When you'r creating an NSDictionary, the order will not be the same. I often recognized that dictionaries get ordered by key-name alphabetically.

But when using dictionaries the order doesn't really matter. And they shouldn't!




回答3:


As the previous answers mentions dictionaries are by nature without order, but you can find here a nice class of OrderedDictionary:

http://www.cocoawithlove.com/2008/12/ordereddictionary-subclassing-cocoa.html

http://projectswithlove.com/projects/OrderedDictionary.zip



来源:https://stackoverflow.com/questions/16081104/how-to-retain-order-of-json-data-retrieved-with-afnetworking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!