2014-03-12 50 views
1

我有以下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; 

} 
+0

首先,這不是一個JSON文件(這不是挑剔)。您省略了非常關鍵的前導'{'(也可能是後面的'}' - 我沒有算過)。 JSON文件中的每個字符都有含義,您必須學習如何正確讀取它們。 –

+0

至於JSON本身,它很醜陋,可能是由不瞭解JSON的人制作的。可能最簡單的方法來處理它(如果你不能得到它的糾正)是將每個「對象」(NSDictionary)的元素複製到相應的數組中 - 相對簡單。 –

+0

我忘了複製領先的{和結尾},但json文件是正確的,我使用在線json驗證器進行了驗證。 – nabrugir

回答

0

我終於結束了改變的JSON:

{ 
    "promotions": [ 
     { 
      "id": "1", 
      "title": "promotion title", 
      "products": [ 
       { 
        "id": "1", 
        "title": "product title", 
        "description": "description" 
       }, 
       { 
        "id": "2", 
        "title": "product title", 
        "description": "description" 
       } 
      ] 
     }, 
     { 
      "id": "2", 
      "title": "promotion title", 
      "products": [ 
       { 
        "id": "6", 
        "title": "product title", 
        "description": "description" 
       } 
      ] 
     } 
    ] 
} 

這就是我如何解析JSON:

- (NSArray *) infoFromJSON{ 
    // Create a NSURLRequest with the given URL 
    NSURL *url=[NSURL URLWithString:urlJSON]; 

    NSURLRequest *request = [NSURLRequest requestWithURL:url 
              cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData 
             timeoutInterval:30.0]; 
    // Get the data 
    NSURLResponse *response; 
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; 

    //Create an array to hold all the information 
    NSMutableArray *info = [[NSMutableArray alloc] init]; 

    // Now create a NSDictionary from the JSON data 
    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 

    NSArray *arrayPromotions = [jsonDictionary objectForKey:@"promotions"]; 

    for(NSDictionary *dictCategories in arrayPromotions) { 
     Block *promotion = [[Block alloc] initWithJSONDictionary:dictCategories]; 

     NSArray *arrayProducts = [dictCategories objectForKey:@"products"]; 

     promotion.questions = [[NSMutableArray alloc] init]; 
     for(NSDictionary *dictProducts in arrayProducts) { 
      Product *product = [[Product alloc] initWithJSONDictionary:dictProducts]; 
      NSLog(@"product title %@", product.title); 
      [promotions.product addObject:product]; 
     } 

     [info addObject:promotion]; 
     NSLog(@"Promotion: %@ product 2: %@", promotion.title, [[promotion.products objectAtIndex:1] title]); 
    } 

    // Return the array of Location objects 
    return info; 

} 

我定義的兩個數據類實現的方法initWithJSONDictionary(促進和產品)

- (id)initWithJSONDictionary:(NSDictionary *)jsonDictionary {  
    if(self = [self init]) { 
     self.title = [jsonDictionary objectForKey:@"title"]; 
    } 
    return self; 
} 
1

這是討厭的JSON。如果可以的話,改變它。目前你有一些字典,字典中的鍵是數字。這些字典應該是數組。

你已經編寫了你的​​代碼,就好像它們是數組一樣。

如果您需要保留JSON,請先讀取字典,然後迭代該鍵,或者,如果可以(因爲您沒有使用鍵進行排序),只需將所有值作爲數組從字典和迭代。

理想的情況下,改變JSON和使用RestKit ...

+0

當你說改變json時,你的意思是隻刪除ID嗎?我可以試着問他們是否可以更改json,但最簡單和更快的解決方案是嘗試解析它而不更改json。 – nabrugir

+0

然後在促銷字典中使用'allValues'。我越是看JSON越糟糕,你應該真的改變了...... – Wain

+0

不。他的意思是與設計JSON輸出的人交談,告訴他們一些在stackoverflow上的有頭腦的人難以置信地搖頭。關於他們生產的JSON,並請他們請請請更改它。 – gnasher729

6

您的JSON並不明確,你必須嘗試使用​​類似:

[{"promotion_id": 1 
    "title": "promotion title", 
    "products": [{"product_id": 1, 
       "title": "product title", 
       "description": "this is the description" 
       }, 
       {"product_id": 2, 
       "title": "product title", 
       "description": "this is the description" 
       }, 
       ... 
       ] 
}, 
{"promotion_id": 2 
    "title": "promotion title", 
    "products": [{"product_id": 3, 
       "title": "product title", 
       "description": "this is the description" 
       }, 
       {"product_id": 4, 
       "title": "product title", 
       "description": "this is the description" 
       }, 
       ... 
       ] 
}, 
... 
] 

然後,解析JSON字典到自定義對象我建議你使用類別NSObject+Motis我最近一直在工作。將JSON字典映射到您的自定義Objective-C對象中非常有用。

主要是,你必須做到:

@interface Promotion : NSObject 
@property (nonatomic, assing) NSInteger promotionId; 
@property (nonatomic, strong) NSString *title; 
@property (nonatomic, strong) NSArray *products; 
@end 

@implementation Promotion 
- (NSDictionary*)mjz_motisMapping 
{ 
    return @{@"promotion_id" : @"promotionId", 
      @"title" : @"title", 
      @"products" : @"products", 
      }; 
} 

- (NSDictionary*)mjz_arrayClassTypeMappingForAutomaticValidation 
{ 
    return @{"products": [Product class]}; 
} 

@end 

@interface Product : NSObject 
@property (nonatomic, assing) NSInteger productId; 
@property (nonatomic, strong) NSString *title; 
@property (nonatomic, strong) NSArray *productDescription; 
@end 

@implementation Promotion 
- (NSDictionary*)mjz_motisMapping 
{ 
    return @{@"product_id" : @"productId", 
      @"title" : @"title", 
      @"description" : @"productDescription", 
      }; 
} 
@end 

,然後通過做執行解析:

- (void)parseTest 
{ 
    NSData *data = jsonData; // <-- YOUR JSON data 

    // Converting JSON data into array of dictionaries. 
    NSError *error = nil; 
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; 

    if (error) 
     return; // <--- If error abort. 

    NSMutableArray *promotions = [NSMutableArray array]; 
    for (NSDictionary *dict in jsonArray) 
    { 
     Promotion *promotion = [[Promotion alloc] init]; 
     [promotion mjz_setValuesForKeysWithDictionary:dict]; 
     [promotions addObject:promotion]; 
    } 
} 

你可以閱讀它是如何工作在這個崗位:​​

希望能有助於你儘可以幫助我。