2016-03-14 88 views
1

我有以下的JSON:如何解析目標C中的JSON字符串?

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

我需要從JSON中提取數據爲字符串

  1. NSString的溫度
  2. 的NSString溼度
  3. 的NSString NO2

如何正確地做?

回答

4

使得NSURL要求在完成塊U可以做到這一點後: -

NSMutableDictionary *s = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; 
    NSString *temperature =[s objectForKey:@"temperature"]; 
    NSString *humidity = [s objectForKey:@"humidity"]; 
5

可以使用NSJSONSerialization類。首先,您需要將字符串轉換爲NSData對象,然後您將獲得JSON數據。看看代碼

// 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); 
     } 
    }