0

How to parse such a JSON using JSONModel ?

[{
    "Value": "Cat",
    "Id": 1
}, {
    "Value": "Dog",
    "Id": 2
}, {
    "Value": "Elephant",
    "Id": 3
}]

if there was something like this:

{
    animals: [{
        "Value": "Cat",
        "Id": 1
    }, {
        "Value": "Dog",
        "Id": 2
    }, {
        "Value": "Elephant",
        "Id": 3
    }]
}

There would be no problem. I would just use:

@property (strong, nonatomic) NSArray <AnimalModel> *animalsArray;

But what can I do if i don't have the "animals" key in the JSON file?

madLokesh
  • 1,860
  • 23
  • 49
Marx Dzida
  • 61
  • 3

3 Answers3

0

Since, you want the first model instead of second, you are not having object-keys but you do have value arrays with key-value pairs.Your complete JSON would be initialized as NSArray rather than NSDictionary You can try the following:

-(void)loadJSON{
  /* * * * NSURLRequest to fetch the json in NSData format * * */

 //Parsing JSONData 
 NSError *err;
 if(responseData != nil){

    NSArray *JSONParser = [NSJSONSerialization jsonObjectWithData:responseData options:kNilOptions error:&err];
    if(!err){

          [key1MutableArray addObject:[JSONParser valueForKey:@"Value"]];
          [key2MutableArray addObject:[JSONParser valueForKey:@"Id"]];           
     }else{
          NSLog(@"JSON Error: %@", err.localisedDescription);
     }
  }else{
          NSLog(@"responseData is NIL");
  }
 }
        NSLog(@"%@", key1MutableArray);
}       NSLog(@"%@", key2MutableArray);

Let me know if this helps.

madLokesh
  • 1,860
  • 23
  • 49
  • It's not exactly what I would like to achieve. You are using NSJSONSerialization. I would like to use JSONModel methods to parse this file. But thanks anyway. – Marx Dzida Oct 16 '14 at 07:08
  • Please tell us why you want to use some third party library instead of the library that is built into iOS and MacOS X, that everyone uses, and that everyone knows? – gnasher729 Oct 16 '14 at 08:44
  • I use JSONModel because it can easily convert a json model collection into specified objects or array of specified objects. I'm not sure if it is possible in NSJSONSerialization. – Marx Dzida Oct 16 '14 at 11:32
0

For the second json response below will be the code.

 id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

    NSArray *array = (NSArray *)jsonObject;
    for(int i=0;i<[array count];i++)
    {
        dict = [array objectAtIndex:i];
        [valueArray addObject:[dict objectForKey:@"Value"]];
        [idArray addObject:[dict objectForKey:@"Id"]];
    }
vishnu
  • 715
  • 9
  • 20
0

You could try creating models as a collection

NSArray *jsonArray = //Array of Dictionaries
NSMutableArray *arrayOfModels = [AnimalObject arrayOfModelsFromDictionaries:jsonArray];
Anupdas
  • 10,211
  • 2
  • 35
  • 60