解析无效的JSON Swift 4
我的Json看起来像这样:
My Json looks like this:
data = { "key":"value",
"key":"value",
"key":"value"}
我一直在尝试使用Swift4 Codable协议来解析JSON,并已使用它产生了很大的效果,但是对于我来说,我无法破坏这种结构.外部data =
使它成为无效的JSON,但在尝试将其传递给JSONDecoder之前,我似乎找不到任何修改数据的方法.
I've been trying to use Swift4 Codable protocols for parsing JSON and have used it to great effect but for the life of me I cannot break this structure. The outer data =
makes it invalid JSON but I can't seem to find any way to modify the data before I attempt to pass it to the JSONDecoder.
有什么办法可以将数据作为字符串接收,以便删除最外面的字符并仅解析剩余的JSON对象?
Is there any way I can just receive that data as a string so I can drop the outermost characters and just parse the remaining JSON object?
如果JSON序列化失败,并且您想更正格式错误的数据(并且无法修复API响应),则可以将数据转换为字符串,修改字符串以创建有效的JSON,然后转换回数据并将其解码为模型对象.对于上述情况:
If JSON serialization is failing and you want to correct the malformed data (and fixing the API response isn't an option) you can convert the data to a string, modify the string to create valid JSON, then convert back to data and decode that into your model object. For the case above:
func normalizeJSON(data: Data) -> Data? {
guard let stringRepresentation = String(data: data, encoding: .utf8) else { return nil }
let validJSONString = stringRepresentation.dropFirst(6)
return validJSONString.data(using: .utf8)
}