gpt4 book ai didi

ios - NSJSONSerialization JSONObjectWithData,其中数据包含换行符

转载 作者:行者123 更新时间:2023-12-01 16:40:01 25 4
gpt4 key购买 nike

示例代码:

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}

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

最佳答案

是的,需要双反斜杠。但是斜杠不需要写两次。
例如,
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\"]"

关于ios - NSJSONSerialization JSONObjectWithData,其中数据包含换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25216159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com