【问题标题】:iOS How to retrieve value from JSON after retrieving web response dataiOS 检索 Web 响应数据后如何从 JSON 中检索值
【发布时间】:2015-12-30 03:59:17
【问题描述】:

我正在尝试发出 nsurl 请求并设法检索出 Web 响应数据。问题是我想从 JSON 列表中检索特定参数。 我要检索的参数是“id”并将其显示在标签中。

这是我用于建立连接的 viewDIDLoad:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.


    feeds = [[NSMutableArray alloc] init];

     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://coolsoft.mousy.com/v1/messi/reports"]];

    // Prepare the variables for the JSON response


    // Create a mutable copy of the immutable request and add more headers
    NSMutableURLRequest *mutableRequest = [request mutableCopy];

    [mutableRequest addValue:@"application/json" forHTTPHeaderField:@"request"];
    // Make synchronous request

    request = [mutableRequest copy];

    // Log the output to make sure our new headers are there
    NSLog(@"%@", request.allHTTPHeaderFields);




    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];

    if(connection)
    {
        _webResponseData = [NSMutableData data] ;


    }
    else
    {
        NSLog(@"Connection is NULL");
    }

}

他是我的connectionDidFinishLoading方法:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSLog(@"Received %lu Bytes", (unsigned long)[_webResponseData length]);
//    NSString *theXML = [[NSString alloc] initWithBytes:
//                        [_webResponseData mutableBytes] length:[_webResponseData length] encoding:NSUTF8StringEncoding];

    // convert to JSON
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.webResponseData options:NSJSONReadingMutableLeaves error:&myError];
    NSString *icon;
    // show all values
    for(id key in res) {

        id value = [res objectForKey:key];

        NSString *keyAsString = (NSString *)key;
        NSString *valueAsString = (NSString *)value;

        NSLog(@"key: %@", keyAsString);
        NSLog(@"value: %@", valueAsString);
    }

    // extract specific value...
    NSArray *results = [res objectForKey:@"id"];

    for (NSDictionary *result in results) {
      icon   = [result objectForKey:@"id"];
        NSLog(@"icon: %@", icon);

    }

    output.text = icon;


    output = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 100)]; //adjust label size and position as needed
    output.font = [UIFont fontWithName:@"BradleyHandITCTT-Bold" size: 23.0];
    output.textColor = [UIColor whiteColor];
    output.textAlignment = NSTextAlignmentCenter;
    output.numberOfLines = 0; //note: I said number of lines need to be 2
    output.backgroundColor = [UIColor clearColor];
    output.adjustsFontSizeToFitWidth = YES;
    output.tag = 100;
}

这是我对 res 字典进行 NSLOG 时的输出:

( { date = "2014-08-28T00:00:00Z"; id = 300005; title = "July 2014 USAA Phishing Campaign Uses KeNiHaCk Exploit"; uri = "/v1/joker/reports/300005"; }, { date = "2014-12-16T20:46:29Z"; id = 300062; title = "Two-Year Chinese Spearphishing Campaign Largely Targeted Japanese Aerospace and Energy Industries"; uri = "/v1/joker/reports/300062"; },

这是我的错误信息:

-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x136713360
2015-12-30 11:58:17.692 FYP_IOS_APP[817:323807] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x136713360'

【问题讨论】:

  • 这已经被问了一千次了,你必须把你的json转换成字典然后用key-value检索数据,问之前请先google一下
  • NSArray *results = [res objectForKey:@"id"];这是错误的。你得到的是字符串而不是数组。

标签: ios objective-c arrays json rest


【解决方案1】:

您的 JSON 响应是 {"id":300005,"title":"pink","date":"2014-08-28T00:00:00Z","uri":"www.hipster.com/hip "}}

所以,你可以使用 lblName.text = [res valueForKey:@"id"];

【讨论】:

    【解决方案2】:

    你的 json 解析没问题,它给你 JSON 到 NSDictionary
    但是您需要在传递 NSDictionary 对象时进行一些小的更改,如下所示。

    查看下面的代码,它可能会对您有所帮助

    -(void)connectionDidFinishLoading:(NSURLConnection *)connection {
        //{"id":300005, "title":"pink", "date":"2014-08-28T00:00:00Z", "uri":"www.hipster.com/hip"}
        NSLog(@"Received %lu Bytes", (unsigned long)[_webResponseData length]);
    
        // convert to JSON
        NSError *myError = nil;
        NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.webResponseData options:NSJSONReadingMutableLeaves error:&myError];
        NSString *icon;
    
        // show all values
        for(id key in [res allKeys]) {
            NSLog(@"key: %@", key);
            NSLog(@"value: %@", [res objectForKey:key]);
        }
    
        // extract specific value...
        icon = [res valueForKey:@"id"];
        NSLog(@"icon: %@", icon);
    
        output.text = icon;
    
        output = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 100)]; //adjust label size and position as needed
        output.font = [UIFont fontWithName:@"BradleyHandITCTT-Bold" size: 23.0];
        output.textColor = [UIColor whiteColor];
        output.textAlignment = NSTextAlignmentCenter;
        output.numberOfLines = 0; //note: I said number of lines need to be 2
        output.backgroundColor = [UIColor clearColor];
        output.adjustsFontSizeToFitWidth = YES;
        output.tag = 100;
    }
    

    更新

    // convert to JSON
    NSError *myError = nil;
    NSArray *res = [NSJSONSerialization JSONObjectWithData:self.webResponseData options:NSJSONReadingMutableLeaves error:&myError];
    
    // show all values
    for(NSDictionary *dic in res) {
        for(NSString *key in [dic allKeys]) {
            NSLog(@"key: %@", key);
            NSLog(@"value: %@", [dic objectForKey:key]);
        }
    }
    

    【讨论】:

    • -[__NSCFArray allKeys]:无法识别的选择器发送到实例 0x13eecdea0 2015-12-30 13:46:33.679 FYP_IOS_APP[864:338722] *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因: '-[__NSCFArray allKeys]: 无法识别的选择器发送到实例 0x13eecdea0'
    • 当我注销 res 的响应时,它显示:( { date = "2014-08-28T00:00:00Z"; id = 300005; title = "July 2014 USAA 网络钓鱼活动使用 KeNiHaCk Exploit"; uri = "/v1/joker/reports/300005"; }, { date = "2014-12-16T20:46:29Z"; id = 300062; title = "为期两年的中国鱼叉式钓鱼活动主要针对日本航空航天和能源工业"; uri = "/v1/joker/reports/300062"; },
    • @zac 你调试过代码吗? & 应用程序在循环开始时是否给出错误?因为这似乎是其他问题,或者您可能在回复中收到 NSArray 并将其解析为 NSDictionary
    • @zac 首先通过NSLog(@"%@",[res class]) 检查您的res 类类型,如果它是NSArray Type,然后使用NSArray *res insted NSDictionary *res 并相应地解析您的数据。
    猜你喜欢
    • 1970-01-01
    • 2020-06-18
    • 2019-01-12
    • 1970-01-01
    • 2023-03-15
    • 2017-08-10
    • 2020-03-12
    • 2019-04-17
    • 2014-01-03
    相关资源
    最近更新 更多