【问题标题】:NSJSONSerialization JSONObjectWithData where data contains line break charactersNSJSONSerialization JSONObjectWithData 其中数据包含换行符
【发布时间】:2014-08-09 07:10:15
【问题描述】:

示例代码:

NSString *jsonObject = ...;
BOOL isValidJSONObject = [NSJSONSerialization isValidJSONObject:jsonObject];
id jsonResponse = [NSJSONSerialization JSONObjectWithData:parsedData
                                                                options:NSJSONReadingAllowFragments
                                                                  error:&jsonError];

问题:

如果jsonObject 包含带有换行符的字符串数据,则NSJSONSerialization 无法解析并返回有效的jsonRespone 对象。它返回以下错误:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unescaped control character around character 119.) UserInfo=0x10ba9fef0 {NSDebugDescription=Unescaped control character around character 119.}

示例 JSON 字符串(带有换行符):

{"Name" : "Lorum","Description" : "Sample: 
Lorum ipsum","Quantity" : 1,"Type" : 1}

处理这种情况的最佳方法是什么?在这种情况下,换行符/换行符应该是有效的。

【问题讨论】:

  • 这不是有效的 JSON。应该转义换行符。
  • @duci9y 当你说“逃跑”时,你到底是什么意思?
  • 现在,我只是用
    标签更改了换行符,然后将
    替换为换行符(在应用程序端)。或者,我可以对数据进行编码。我不喜欢这种方法。我认为 NSJSONSerialization 应该处理换行符(\n 和 \r)。 JSONKit 使用选项 JKParseOptionUnicodeNewlines 来处理这个问题,我喜欢这样!
  • JSONKit 为您提供了该选项。根据标准,您的 JSON 仍然不正确。

标签: ios json nsjsonserialization


【解决方案1】:

是的,需要双反斜杠。但是斜线不需要写两次。 例如,

jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:@[@"line 0\nline1", @"http://twitter.com"] options:0 error:nil] encoding:NSUTF8StringEncoding];

当您将光标悬停在jsonString 上时,Xcode 会告诉您它到底想要什么。如果你写

jsonString = @"[\"http://twitter.com\"]",

使用 NSJSONSerialization 解析字符串时可以得到正确答案。即使你知道更合适的输入是

jsonString = @"[\"http:\\/\\/twitter.com\"]".

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 2011-03-17
    • 1970-01-01
    • 2022-06-28
    相关资源
    最近更新 更多