问题
My Json looks like this:
data = { "key":"value",
"key":"value",
"key":"value"}
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.
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?
回答1:
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)
}
回答2:
func parseSomeUrl {
let someUrl = "http://api.someurl.com"
guard let url = URL(string: someUrl) else {return}
URLSession.shared.dataTask(with: url) {(myResponse, response, err) in
guard let data = data else {return}
do {
let data = try JSONDecoder().decode(myResponse.self, from: data)
}
} catch let jsonErr {
print("Error serializing json:", jsonErr)
}
}.resume()
来源:https://stackoverflow.com/questions/46488675/parsing-invalid-json-swift-4