0

How should I parse JSONs with format:

{
"1": {
    "name": "Бекон",
    "unit": "гр."
},
"2": {
    "name": "Бульон куриный",
    "unit": "ст."
}

}

and:

{
  "recipeCode" : "00001",
  "inCategory" : "12",
  "recipe" : "Зимний тыквенный суп",
  "difficulty" : 2,
  "personCount" : 4,
  "prepHour" : 1,
  "prepMin" : 30,
  "comments" : "При подаче добавить сметану, крутоны и присыпать сыром",
  "ingredients" : {
    "2" : 3,
    "11" : 2,
    "13" : 1,
    "14" : 2,
    "19" : 1
  }
}

The second one I even didn't try... But with the first one I have some problems. I do this:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Ingredients" ofType:@"json"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
NSDictionary *ingredients = [NSJSONSerialization JSONObjectWithData:myData options:kNilOptions error:&error];

and than I have ingredient dictionary with two key/value pairs. Both of them contains key "1" and value "1 key/value pairs" and nothing about "name" or "unit" values.

Any help how to correctly parse such JSONs

Romowski
  • 1,518
  • 5
  • 25
  • 50
  • When I execute your code the JSON is correctly parsed. Please provide a better illustration of why it does not work for you. Can you NSLog the dictionary and include your output. – ColinE Apr 24 '13 at 05:15
  • NSLog shows everything (but "debug window" didn't show).. ok, this works, but how to read this internal data? – Romowski Apr 24 '13 at 05:31
  • How do you want to display data? – Anupdas Apr 24 '13 at 05:38

1 Answers1

1

You are parsing it correctly,and what you will have output will be there in the dictionary

The parsing gives output as objects as NSDictionary and array as NSArray

so in your case the key 1 and key 2 have value a NSDictionary itself

enter image description here

NSDictionary *dict1 = [ingredients objectForKey:@"1"];
NSDictionary *dict2 = [ingredients objectForKey:@"2"];

and value as

NSString *name=[dict1 objectForKey:@"name"];
NSString *unit=[dict1 objectForKey:@"unit"];
Lithu T.V
  • 19,955
  • 12
  • 56
  • 101
  • yeah!!! I understand how it works. Thanks! So the second file is a dictionary and **ingredients** is an object with dictionary in it. Am I right? – Romowski Apr 24 '13 at 05:47
  • yeah thats it.If it is an object representation {} then it is dictionary and if array [] then it is nsarray returned – Lithu T.V Apr 24 '13 at 05:48