【问题标题】:How to parse invalid JSON in Objective-C如何在 Objective-C 中解析无效的 JSON
【发布时间】:2016-12-09 12:38:57
【问题描述】:

我想解析一个对 Objective-C 无效的 JSON 数据,但是这个 JSON 包含一个有效的 JSON 数组和一个由“~”分隔的值。

我的 JSON 是这样的:

[
    {"id":"553",
    "parent_id":"0",
    "user_id":"0",
    "name":"testnav",
    "img_name":"8mS5ximage56.jpg",
    "img_path":"gallery/category/8mS5ximage56.jpg",
    "title":"",
    "description":"test",
    "position":"0",
    "status":"1",
    "update":"0",
    "app_id":"2",
    "multi":"0",
    "branch_id":"0"
    },
    {
    "id":"554",
    "parent_id":"0",
    "user_id":"0",
    "name":"test_Cat_for_iamgeUp",
    "img_name":"q5aW61.jpg",
    "img_path":"gallery/category/q5aW61.jpg",
    "title":"",
    "description":"desc",
    "position":"0",
    "status":"1",
    "update":"0",
    "app_id":"2",
    "multi":"0",
    "branch_id":"0"
    },
    {
    "id":"555",
    "parent_id":"0",
    "user_id":"0",
    "name":"test category",
    "img_name":"enSoW1.jpg",
    "img_path":"gallery/category/enSoW1.jpg",
    "title":"",
    "description":"desc",
    "position":"0",
    "status":"1",
    "update":"0",
    "app_id":"2",
    "multi":"0",
    "branch_id":"0"
    }
]~200

如果我试图通过NSJSONSerialization 方法解析它,它会给出类似{NSDebugDescription=Garbage at end.} 的错误。

有什么方法可以捕获额外的值并解析 JSON 吗?

【问题讨论】:

  • 删除你的字符串的~200,但更重要的是,为什么你最后有~200?这才是真正的问题:服务器?
  • 我可以从字符串中删除 ~200 但我没有字符串,我有从服务器获取的 NSData。
  • NSString *jsonStr = [[NSString alloc] initWithData:yourJSONData encoding:NSUTF8StringEncoding]; NSString *cleanJSONStr = //"remove the ~200 from jsonStr"; NSData *cleanJSONData = [cleanJSONStr dataUsingEncoding:NSUTF8StringEncoding]; NSArray *yourReponse = [NSJSONSerialization ...:cleanJSONData ...]; ?
  • 是的,这很有帮助。谢谢@Larme
  • 虽然错误信息非常好!

标签: ios objective-c arrays json


【解决方案1】:

错误显然在服务器端。我强烈建议与他们联系,以便它提供正确的 JSON。
但是,有时,您无法控制他们,或者无法联系他们,或者他们现在不会修复它,而您仍有工作要做。

因此,这不是推荐的方法,只是绕过您的问题的一种方法,因为响应应该是有效的 JSON,但为了不被卡住:

NSError *errorJSONSerialization = nil;
NSArray *yourResponse = [NSJSONSerialization JSONObjectWithData: yourJSONData options:kNilOptions error:&errorJSONSerialization];
if (errorJSONSerialization) //Could it because because of the garbage at the end?
{
    NSString *jsonStr = [[NSString alloc] initWithData:yourJSONData encoding:NSUTF8StringEncoding]; 
    NSString *cleanJSONStr = //"remove the ~200 from jsonStr", there are various ways, according to how it may change: is it always ~200, or could it be in some case ~100, etc. 
    NSData *cleanJSONData = [cleanJSONStr dataUsingEncoding:NSUTF8StringEncoding]; 
    yourResponse = [NSJSONSerialization JSONObjectWithData: cleanJSONData options:kNilOptions error:nil];
}

【讨论】:

    猜你喜欢
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多