如何纠正此错误:JSON 错误:无法读取数据,因为格式不正确?
struct LanguageText: Decodable {
let id_language: Int
let language_text: String
}
func textLoad() {
let switchcase = "loginWords"
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "switchcase=\(switchcase)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
return // check for fundamental networking error
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print("JSON error: \(error.localizedDescription)")
}
}.resume()
}
这是 JSON 格式:
[{"id_language":"15","language_text":"Female"},
{"id_language":"16","language_text":"Male"},
{"id_language":"17","language_text":"Other"},
{"id_language":"1000","language_text":"Hello there!"}]
谢谢!
最佳答案
您正在尝试将 id_language 放入 Int-Value 中,但在 JSON 中 id_language 是 String。
将 id_language 更改为字符串
struct LanguageText: Decodable {
let id_language: String
let language_text: String
}
或者你必须编辑你的 JSON 文件
[{"id_language":15,"language_text":"Female"},
{"id_language":16,"language_text":"Male"},
{"id_language":17,"language_text":"Other"},
{"id_language":1000,"language_text":"Hello there!"}]
对于解析 JSON,我可以推荐 this site
关于ios - SWIFT - JSON 错误 : The data couldn’t be read because it isn’t in the correct format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59115450/