我有以下json文件,我試圖從iOS應用程序解析它。我定義了一個解析文件的方法,但我不知道如何處理整數,它們是ID。我想把數據放在一個數組(促銷),其中包含一個標題和一個產品陣列(下面更好地解釋)。任何建議或良好的參考?在iOS中解析json並向對象數組添加值
JSON文件:
"promotions": {
"1": {
"title": "promotion title",
"product": {
"1": {
"title": "product title",
"description": "this is the description"
},
"2": {
"title": "product title",
"description": "this is the description"
}
}
},
"2": { "3": {
"title": "product title",
"description": "this is the description"
},
"4": {
"title": "product title",
"description": "this is the description"
}
}
}
}
這是我的數據類:
Promotion { NSString *title; NSArray *products;}
Product { NSString *title; NSString *description;}
而我的函數加載JSON和,加上所有的對象在促銷的數組,它包含每個促銷活動,一系列產品。
- (NSArray *) infoFromJSON{
NSURL *url=[NSURL URLWithString:urlJSON];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:30.0];
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSMutableArray *promotions = [[NSMutableArray alloc] init];
NSArray *array = [jsonDictionary objectForKey:@"promotions"];
NSLog(@"array: %@", array);
NSLog(@"items en array %d", [array count]);
NSLog(@"object 1 en array: %@", [array objectAtIndex:1]);
// Iterate through the array of dictionaries
for(NSDictionary *dict in array) {
Promotion *promotion= [[Promotion alloc] initWithJSONDictionary:dict];
// Add the promotion object to the array
[promotions addObject:promotions];
//Add the products to each promotion??
}
// Return the array of promotion objects
return promotions;
}
首先,這不是一個JSON文件(這不是挑剔)。您省略了非常關鍵的前導'{'(也可能是後面的'}' - 我沒有算過)。 JSON文件中的每個字符都有含義,您必須學習如何正確讀取它們。 –
至於JSON本身,它很醜陋,可能是由不瞭解JSON的人制作的。可能最簡單的方法來處理它(如果你不能得到它的糾正)是將每個「對象」(NSDictionary)的元素複製到相應的數組中 - 相對簡單。 –
我忘了複製領先的{和結尾},但json文件是正確的,我使用在線json驗證器進行了驗證。 – nabrugir