ObjectiveC的JSON解析

时间:2017-12-12 02:16:01

标签: objective-c json xcode

如何从下面的JSON数据中获取详细数据? 我使用了Objective-C。

{
  "success" : "Y"
  "data": [
    {
      "insertId": "1",
    }
  ]
  "err" : ""
}

2 个答案:

答案 0 :(得分:0)

您需要哪些确切的数据。

如果您收到回复,请在

中获取该回复
  NSDictionary *data = [NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];

对于数据:

   NSArray *array=[dictionary objectforKey:@"data"];

你得到数组[{“insertId”:“1”,}]

    NSdictionary *dict=[array objectAtIndex:0];

你在数组中找到字典{“insertId”:“1”,}

答案 1 :(得分:0)

我会给你详细解决方案。

首先,当你得到响应检查时,是否以数组或字典开头。

id jsonRes = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

我检查了你的回答。它从字典开始。如果你有一些疑问,请检查以下条件。之后使用密钥从响应中获得结果。

if([jsonRes isKindOfClass:[NSDictionary class]]){
        NSDictionary *dictRes = [jsonRes copy];
        NSString *strSuccess = [dictRes objectForKey:@"success"];
        NSString *strError = [dictRes objectForKey:@"err"];
        NSString *strInsertedId = [[[dictRes objectForKey:@"data"]objectAtIndex:0] objectForKey:@"insertId"];

        NSLog(@"The Success is - %@",strSuccess);
        NSLog(@"Error is - %@",strError);
        NSLog(@"Inserted id is - %@",strInsertedId);
    }
else {
        NSLog(@"The response starts with array");
}

下面我手动尝试了你的代码,它运行正常。我使用字符串创建了json并检查了结果。

NSString *strJson = @"{ \"success\": \"Y\", \"data\": [{\"insertId\": \"1\" }],\"err\": \"\"}" ;
NSError *jsonError;
NSDictionary *dictRes =  [NSJSONSerialization JSONObjectWithData: [strJson dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
NSLog(@"The response are - %@",dictRes);
NSString *strSuccess = [dictRes objectForKey:@"success"];
NSString *strError = [dictRes objectForKey:@"err"];
NSString *strInsertedId = [[[dictRes objectForKey:@"data"]objectAtIndex:0] objectForKey:@"insertId"];

NSLog(@"The Success is - %@",strSuccess);
NSLog(@"Error is - %@",strError);
NSLog(@"Inserted id is - %@",strInsertedId);

输出结果是

enter image description here