iOS Error Domain=NSCocoaErrorDomain Code=3840 解析带等号(=)的json字符串
解析json字符串的时候报错: 第一个字符应该是key的字符串。
·
解析json字符串的时候
“{timeInterval=60, stepList=[0, 0, 0, 186, 1928, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 296, 0, 0, 0, 0, 0]}”
报错: 第一个字符应该是key的字符串
Error Domain=NSCocoaErrorDomain Code=3840 “No string key for value in object around character 1.” UserInfo={NSDebugDescription=No string key for value in object around character 1.}
原因
字符串不是标准的json字符串,标准的字符串应该长成下面的样子
"{\"timeInterval\":60, \"stepList\":[0, 0, 0, 186, 1928, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 296, 0, 0, 0, 0, 0]}"
解析带等号(=)的json字符串
class C1StepModel:Decodable {
var timeInterval:Int = 60
var stepList:[Int] = [1,2]
}
var jsonStr = "{timeInterval=60, stepList=[0, 0, 0, 186, 1928, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 296, 0, 0, 0, 0, 0]}"
jsonStr = jsonStr.replacingOccurrences(of: "=", with: ":")
jsonStr = jsonStr.replacingOccurrences(of: "timeInterval", with: "\"timeInterval\"")
jsonStr = jsonStr.replacingOccurrences(of: "stepList", with: "\"stepList\"")
let data:Data = jsonStr.data(using: .utf8)!
let model = try! JSONDecoder().decode(C1StepModel.self, from: data)
更多推荐
已为社区贡献2条内容
所有评论(0)