【问题标题】:how to cast response object to an object如何将响应对象转换为对象
【发布时间】:2017-02-06 12:25:22
【问题描述】:
[manager POST:urlString parameters:[self jsonDict] success:^(AFHTTPRequestOperation *operation, id responseObject){

        NSLog(@"response data: %@", responseObject);


        NSArray *postFromResponse = [ responseObject valueForKeyPath:@"credentials"];
    NSLog(@"credentials:%@", postFromResponse);

        for(NSDictionary *object in postFromResponse)
        {
            NSString *AccessKeyId = [object valueForKeyPath:@"AccessKeyId"];
            NSLog(@"%@", AccessKeyId);
        }



}

它给了我错误:

由于未捕获的异常“NSUnknownKeyException”而终止应用程序, 原因:'[<__nscfstring> valueForUndefinedKey:]:这个类 不符合键 AccessKeyId 的键值编码'

【问题讨论】:

  • for(NSDictionary *object in postFromResponse): postFromResponse 似乎有一些 NSString 而不仅仅是 NSDictionary 对象(如果不是全部 NSString)。这就是为什么在objectNSString 的情况下,您不能调用valueForKeyPath。还是因为responseObjectNSString 而不是NSDictionary?。目前尚不清楚是哪一行导致了问题,向我们展示 JSON 可能会有所帮助。
  • 我的回复是:凭证 = { AccessKeyId = abac; SecretAccessKey = "99";会话令牌 = "rt"; };
  • 请用它更新(编辑)您的问题,并指定它是postFromResponse 还是responseObject 的值。
  • 它来自 postFromResponse 值。其内部字典值,如 AccessKeyId、SessionId

标签: objective-c


【解决方案1】:

试试这个:

NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSArray *postFromResponse = [responseDict valueforkey:@"credentials"];
for(NSDictionary *object in postFromResponse) {
  NSString *AccessKeyId = [object valueforkey:@"AccessKeyId"];
  NSLog(@"%@", AccessKeyId);
}

【讨论】:

  • 由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-[__NSDictionaryI bytes]: unrecognized selector sent to instance 0x7a0abc50' ..sorry 它给了我一个错误:
  • 我的回复是:credentials = { AccessKeyId = abac; SecretAccessKey = "99";会话令牌 = "rt"; };
  • 尝试 nsstring *a= [[responseDict valueforkey:@"credentials"]valueforkey:@"AccessKeyId"];
  • 对不起,它给了我 Null 值
  • 如何将此值转换为 nssobject 属性示例:object.accessId 将此值转换为新对象属性时为空
猜你喜欢
  • 2017-10-17
  • 2019-03-15
  • 2022-01-21
  • 2021-08-27
  • 1970-01-01
  • 2021-07-20
  • 1970-01-01
  • 2018-07-26
  • 1970-01-01
相关资源
最近更新 更多