gpt4 book ai didi

swift - NSJSON 序列化错误。 Code=3840 "字符 0 周围的值无效

转载 作者:IT王子 更新时间:2023-10-29 05:51:03 24 4
gpt4 key购买 nike

NSJSONSerialization.JSONObjectWithData 使用像“abc”这样的字符串时出错,但使用“123”时成功

我不知道为什么。


错误日志

2015-11-04 17:42:02.997 SwiftJsonDemo[27196:2701028] Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}

代码

//var str = "123" // ok
var str = "abc" // error
let strData = str.dataUsingEncoding(NSUTF8StringEncoding)

if let d = strData {
let urlStr = String(data: d, encoding: NSUTF8StringEncoding)

do {
let json = try NSJSONSerialization.JSONObjectWithData(d, options: NSJSONReadingOptions.AllowFragments)
} catch let e {
print(e)
}
} else {
print("data error")
}

最佳答案

123

是一个有效的 JSON 数字,因此如果 .AllowFragments 可以将其读取为 JSON选项已设置。 JSON 字符串必须用引号引起来:(详见 http://www.json.org):

"abc"

在 Swift 字符串文字中,这些引号被转义为反斜杠:

let str = "\"abc\"" // OK!
let strData = str.dataUsingEncoding(NSUTF8StringEncoding)
// ...

关于swift - NSJSON 序列化错误。 Code=3840 "字符 0 周围的值无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33518839/

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