如何在目标C中解析JSON字符串?

时间:2016-03-14 05:47:59

标签: objective-c json

我有以下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. 如何正确地做到这一点?

2 个答案:

答案 0 :(得分:11)

您可以使用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);
        }
    }

答案 1 :(得分:7)

在完成块中创建NSURL请求后,您可以这样做: -

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