8

I have the following json:

NSString *s = @"{"temperature": -260.65, "humidity": 54.05, "time": "2016-03-14T09:46:48Z", "egg": 1, "id": 6950, "no2": 0.0}";

I need to extract data from json to strings

  1. NSString temperature
  2. NSString humidity
  3. NSString no2

How to do it properly?

amazingbasil
  • 1,695
  • 3
  • 18
  • 23

2 Answers2

20

you can use NSJSONSerialization class. first you need to convert your string to an NSData object after that you will get the JSON data. have a look on the code

    // json s string for NSDictionary object
    NSString *s = @"{\"temperature\": -260.65, \"humidity\": 54.05, \"time\": \"2016-03-14T09:46:48Z\", \"egg\": 1, \"id\": 6950, \"no2\": 0.0}";
    // comment above and uncomment below line, json s string for NSArray object
    // NSString *s = @"[{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}]";

    NSData *jsonData = [s dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;

    //    Note that JSONObjectWithData will return either an NSDictionary or an NSArray, depending whether your JSON string represents an a dictionary or an array.
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

    if (error) {
        NSLog(@"Error parsing JSON: %@", error);
    }
    else
    {
        if ([jsonObject isKindOfClass:[NSArray class]])
        {
            NSLog(@"it is an array!");
            NSArray *jsonArray = (NSArray *)jsonObject;
            NSLog(@"jsonArray - %@",jsonArray);
        }
        else {
            NSLog(@"it is a dictionary");
            NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
            NSLog(@"jsonDictionary - %@",jsonDictionary);
        }
    }
keshav vishwkarma
  • 1,832
  • 13
  • 20
9

After making the NSURL Request in the completion block u can do this:-

 NSMutableDictionary *s = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];  
    NSString *temperature =[s objectForKey:@"temperature"];
    NSString *humidity = [s objectForKey:@"humidity"];
Shravan
  • 438
  • 3
  • 17