[英]How to parse NSDictionary sequentially?
我需要解析一個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中的鍵順序。
不清楚要什么,想要字典,而您已經在解析字典。 要從JSON獲取字典,請使用以下代碼。
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:receiveData options:kNilOptions error:&error];
要獲取所有密鑰,然后檢索詳細信息,請使用
NSArray *sortedKeys = [[jsonDict allKeys]
擁有鑰匙后,即可獲取詳細信息
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);
}
}
字典是無序集合。 您說“ ...維護init中的鍵順序”。 哪有這回事。
JSON“對象”,即NSDictionaries / Swift字典的JSON等效項,具有相同的問題。
某些JSON庫將保留鍵/值對的發送順序,但是您不應依賴於此。 JSON協議不保證它。
接收JSON數據並將其轉換為NSDictionary
/ Dictionary
,鍵/值對的發送順序就會丟失。 我知道要保留原始JSON數據流中鍵/值對的(已經不可靠)順序的唯一方法是自己解析JSON,而不是使用NSJSONSerialization
反序列化它。
如果要按特定順序排列數據,則應使用數組作為容器對象來發送數據。 您可以根據需要發送一組鍵/值對。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.