How should I read the data from a json string? iphone

一世执手 提交于 2019-12-10 17:34:27

问题


I have in a NSString "[{"van" : 1,312, "vuan":12,123}] and in order to get this values for every key, I am doing this:

    NSData *data1 = [jsonResponse1 dataUsingEncoding:NSUTF8StringEncoding];
    jsonArray = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&err];

    self.van = [NSMutableArray arrayWithCapacity:1];
    self.vuan = [NSMutableArray arrayWithCapacity:1];

    for (NSDictionary *json in jsonArray) {
        NSString * value = [json objectForKey:@"van"];
        [self.van addObject:value];
        lbl1.text = value;

        NSString * value1 = [json objectForKey:@"vuan"];
        [self.vuan addObject:value1];
        lbl4.text = value1;
    }

May be I don't have to use an array and instead to convert the NSData directly in a NSDictionary.

Anyway, I don't understand why jsonArray is nil, although jsonResponse1 contains the values I have written above.

EDIT: My boss have written the json string wrong. Thank you all for your suggestions!:)


回答1:


Your JSON is invalid. Fix it. This site is your friend.

http://jsonlint.com/




回答2:


You need to code more defensively and you need to report errors as they are found.

Firstly check if the JSON parsing failed and if so report the error:

 NSData *data1 = [jsonResponse1 dataUsingEncoding:NSUTF8StringEncoding];
jsonArray = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&err];
if (jsonArray == nil)
{
    NSLog(@"Failed to parse JSON: %@", [err localizedDescription]);
    return;
}

Secondly if those keys are not in the JSON, objectForKey: will return nil and when you attempt to add that to the arrays, it will throw an exception, which is something you want to avoid:

for (NSDictionary *json in jsonArray) {
    NSString * value = [json objectForKey:@"van"];
    if (value != nil)
    {
        [self.van addObject:value];
        lbl1.text = value;
    }
    else
    {
         NSLog(@"No 'van' key in JSON");
    }

    NSString * value1 = [json objectForKey:@"vuan"];
    if (value1 != nil)
    {
        [self.vuan addObject:value1];
        lbl4.text = value1;
    }
    else
    {
        NSLog(@"No 'vuan' key in JSON");
    }
}

So in summary: runtime errors will occur so you need to ensure you handle them. When they occur you need to report them with as much information possible so that you can diagnose and fix them.



来源:https://stackoverflow.com/questions/15265589/how-should-i-read-the-data-from-a-json-string-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!