【问题标题】:Parse encode custom error response解析编码自定义错误响应
【发布时间】:2015-11-10 19:33:59
【问题描述】:

在我的 Parse 云代码中,我有这样的自定义错误

response.error({ 
    "Error" : "DEAL EXPIRED",
    "Title" : "Sorry!",
    "Message" : "This deal is expired :(",
    "Action" : "Ok"
});

因为我想显示一个 UIAlertView,但是我在阅读字典时遇到了问题。我在应用程序中的代码是:

NSDictionary *errorDictionary = [error userInfo];

if ([[errorDictionary objectForKey:@"Error"] isEqualToString:@"DEAL EXPIRED"]) {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:
        [NSString stringWithFormat:@"%@",[errorDictionary objectForKey:@"Title"]]
         message:[NSString stringWithFormat:@"%@",[errorDictionary objectForKey:@"Message"]]
         delegate:nil
         cancelButtonTitle:[NSString stringWithFormat:@"%@",[errorDictionary objectForKey:@"Action"]]
         otherButtonTitles:nil];
    [alert show];

}

errorDictionary的日志是:

{"Error":"DEAL EXPIRED","Title":"Sorry!","Message":"This deal is expired :(","Action":"Ok"}

谢谢

【问题讨论】:

  • 你有什么问题?
  • 代码不进入if语句。也许必须解析字典
  • 如果在if 语句之前执行NSLog(@"the error is: %@",[errorDictionary objectForKey:@"Error"]); 会发生什么?
  • 您打印的日志肯定看起来像 JSON 字符串,而不是 NSDictionary 实例...
  • @Wain 是的,很可能

标签: ios objective-c parse-platform nserror


【解决方案1】:

因为字符串的打印输出为空,这意味着你的if语句永远是假的。因此[error userInfo] 不是NSDictionary 对象。您需要先将 JSON 字符串转换为 dictionary,然后才能将其用作 dictionary

如果它是NSData 对象,这里是一个示例。

NSDictionary * errorDictionary = [NSJSONSerialization JSONObjectWithData:[error userInfo] options:kNilOptions error:&error];

Here is the Apple documentation 如果是NSInputStream 对象。

有更多关于 JSON 到 NSDictionary 转换的信息here

【讨论】:

    猜你喜欢
    • 2014-04-16
    • 2018-01-29
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 2021-11-04
    • 2020-11-27
    • 1970-01-01
    • 2011-10-08
    相关资源
    最近更新 更多