我需要解析一个json并获得与它们在响应中相同的序列中的键值对。
目前我正在做的是
-(instancetype)initWithJson:(NSDictionary *)responseDict {
if (self = [super init]){
NSArray *tempArray = [[NSArray alloc] init];
NSArray *roomSizesForAcArray = [responseDict valueFromDictionaryWithNSNullCheck:@"roomSizesForAc"];
NSArray *loadChartForInverterArray = [responseDict valueFromDictionaryWithNSNullCheck:@"loadChartForInverter"];
if(roomSizesForAcArray && roomSizesForAcArray.count>0){
self.isInverterChart=false;
tempArray=roomSizesForAcArray;
}
else if(loadChartForInverterArray && loadChartForInverterArray.count>0){
self.isInverterChart=true;
tempArray=loadChartForInverterArray;
}
self.arrayOfChartSizeObjects=tempArray;
if(tempArray && tempArray.count>0){
//Temp array first object is a dictionary which i need to parse sequentially
self.arrayOfKeys = [[tempArray objectAtIndex:0] allKeys];
//This array of keys is random every time and not sequential
}
}
return self;
}
我需要解析字典[tempArray objectAtIndex:0]来维护init中键的顺序。
答案 0 :(得分:0)
当你已经解析字典时,不清楚你想要什么,你想要字典。要从JSON中获取字典,请使用以下代码。
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:receiveData options:kNilOptions error:&error];
要获取所有密钥然后检索详细信息,请使用
NSArray *sortedKeys = [[jsonDict allKeys]
获得密钥后,请获取详细信息
答案 1 :(得分:0)
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(@"Item: %@", item);
}
}
答案 2 :(得分:0)
字典是无序集合。你说" ...在init"中维护键的顺序。没有这样的事情。
JSON" Objects",相当于NSDictionaries / Swift Dictionaries的JSON,具有相同的问题。
某些JSON库将保留提交的键/值对的顺序,但您不应该依赖它。 JSON协议不保证它。
收到JSON数据并将其转换为NSDictionary
/ Dictionary
后,键/值对的发送顺序将丢失。我知道保留原始JSON数据流中键/值对的(已经不可靠)顺序的唯一方法是自己解析JSON而不是使用NSJSONSerialization
对其进行反序列化。
如果您希望按特定顺序排列数据,则应使用数组作为容器对象进行发送。如果需要,您可以发送一组键/值对。