Ram*_*mis 3 swift4 jsondecoder
后端返回位置的自定义 JSON 值。如示例所示:
{
"location": (54.000000, 21.000000)
}
Run Code Online (Sandbox Code Playgroud)
为了解析 JSON,我使用以下代码:
let json = """
{
"location": (54.000000, 21.000000)
}
"""
struct Location: Codable {
var latitude: Double
var longitude: Double
}
let dataJson = json.data(using: .utf8)!
let location = try? JSONDecoder().decode(Location.self, from: dataJson)
Run Code Online (Sandbox Code Playgroud)
当我尝试使用 JSONDecoder 创建 Location 对象时,出现错误:给定的数据不是有效的 JSON。
dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 18." UserInfo={NSDebugDescription=Invalid value around character 18.})))
Run Code Online (Sandbox Code Playgroud)
我知道它不是有效的 JSON。重写哪些方法可以解析无效的 JSON 值?
如果第三方以一致的方式生成无效的 JSON,您可以使用正则表达式将其修复回有效的 JSON。这并不是万无一失的。如果 JSON 只是格式不同,则可能会失败。最好的做法是要求第三方纠正其后端。
您可以使用正则表达式将圆括号替换为方括号:
var json = """
{
"location": (54.000000, 21.000000)
}
"""
let regex = try! NSRegularExpression(pattern: "\\\"location\\\":\\s*\\((.+?)\\)", options: [])
let fullRange = NSRange(..<json.endIndex, in: json)
json = regex.stringByReplacingMatches(in: json, options: [], range: fullRange, withTemplate: "\"location\": [$1]")
Run Code Online (Sandbox Code Playgroud)
您还需要向结构添加自定义解码器,Location因为它现在被编码为数组:
struct Location: Decodable {
var latitude: Double
var longitude: Double
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
latitude = try container.decode(Double.self)
longitude = try container.decode(Double.self)
}
}
Run Code Online (Sandbox Code Playgroud)
解码示例:
struct Response: Decodable {
var location: Location
}
let dataJson = json.data(using: .utf8)!
let location = try JSONDecoder().decode(Response.self, from: dataJson)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7976 次 |
| 最近记录: |