Jack Sparrow Jack Sparrow - 5 months ago 10
Objective-C Question

NSJSONSerialization not storing data into array

I have this code in

AppDelegate.m
:

NSError *error;
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"City" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSArray *json = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments error:&error];


NSLog(@"data : %@",data);
NSLog(@"json : %@",json[0]);


And
data
has content but
NSJSONSerialization
is not storing it into variable
json
(it shows
(null)
)

My json file content :

[

“Result”:
{
"ID":"3",
"Name":"Ambegaon",
"Distid":"1050114"
},
{
"ID":"4",
"Name":"Aundh",
"Distid":"1050114"
}
]


Things i have tried:


  1. NSDictionary
    NSArray
    both mutable and non mutable

  2. Changed City.json location

  3. Different options like
    NSJSONReadingMutableContainers
    NSJSONReadingMutableLeaves
    kNilOptions


Answer

It happened because your JSON has invalid format. It not equal array. You need have

[
 {
   "ID":"3",
   "Name":"Ambegaon",
   "Distid":"1050114"
 },
 {
   "ID":"4",
   "Name":"Aundh",
   "Distid":"1050114"
 }
]

without Result key or change your json and parse code to

{
   "Result" : [{
      "ID":"3",
      "Name":"Ambegaon",
      "Distid":"1050114"
    },
    {
      "ID":"4",
      "Name":"Aundh",
      "Distid":"1050114"
    }]
}

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
                                                    options:NSJSONReadingAllowFragments error:&error];
NSArray *arr = json[@"Result"];