-3

My json string is:

jsonData=@"{data:[{\"type\":\"ex\",\"coordinate\":\"19.0760,73.8777\",\"title\":\"Awesome Event 1\"},{\"type\":\"pe\",\"coordinate\":\"19.0760,73.2777\",\"title\":\"Awesome Event 2\"},{\"type\":\"ev\",\"coordinate\":\"19.0760,72.4777\",\"title\":\"Awesome Event 3\"},{\"type\":\"ex\",\"coordinate\":\"19.0760,72.3777\",\"title\":\"Awesome Event 4\"},{\"type\":\"pe\",\"coordinate\":\"19.0760,72.1777\",\"title\":\"Awesome Event 5\"},{\"type\":\"ev\",\"coordinate\":\"19.0760,72.4777\",\"title\":\"Awesome Event 6\"},{\"type\":\"ex\",\"coordinate\":\"19.0760,72.5777\",\"title\":\"Awesome Event 7\"},{\"type\":\"pe\",\"coordinate\":\"19.0760,72.9777\",\"title\":\"Awesome Event 8\"},{\"type\":\"ev\",\"coordinate\":\"19.1760,72.8777\",\"title\":\"Awesome Event 9\"},{\"type\":\"ex\",\"coordinate\":\"19.4760,72.8777\",\"title\":\"Awesome Event 10\"},{\"type\":\"pe\",\"coordinate\":\"19.5760,72.8777\",\"title\":\"Awesome Event 11\"},{\"type\":\"ev\",\"coordinate\":\"19.3760,72.8777\",\"title\":\"Awesome Event 12\"}]}";

How to convert it to NSDictionary?

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
shakshi
  • 231
  • 1
  • 2
  • 9
  • `NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[jsonData dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error]`? I'd rename `jsonData` into `jsonString`, because `Data` may think of `NSData` here. – Larme Oct 05 '16 at 12:00

2 Answers2

1

First of all convert your jsonString into JsonData. As per your code the json is in string format. So follow the below steps.

-> Convert the jsonString to Data -> Convert the data to JsonDict

jsonString to Data

NSData* data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

After that

Data to JsonDict

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

Then you can access the values from the dict using Key names.

Vikram Parimi
  • 777
  • 6
  • 29
  • how to access the field "type" from "data" – shakshi Oct 05 '16 at 12:03
  • You should get an warning at least with that code (and I'd guess a crash at run time), since `jsonData` is a `NSString` object, while the first parameter of `+ (id)JSONObjectWithData: options:error:` should be a `NSData` object. – Larme Oct 05 '16 at 12:03
  • how do you access diectly string to Dictionary, is this possible – Anbu.Karthik Oct 05 '16 at 12:03
  • yes it is possible. Once you convert the data into a dict. Access like this : `[jsonDict valueForKey:@"title"];` – Vikram Parimi Oct 05 '16 at 12:05
0

using NSJSONSerialization class and its method JSONObjectWithData you can convert string to dict or json.

NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//                              OR
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"string: %@",json);
Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38