Reputation: 21
How to correct this error: JSON error: The data couldn’t be read because it isn’t in the correct format?
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()
}
This is the JSON format:
[{"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!"}]
Thanks!
Upvotes: 2
Views: 4575
Reputation: 866
In your model you could do something like this:
struct LanguageText: Decodable {
let languageId: String
let languageText: String
enum CodingKeys: String, CodingKey {
case languageId = "id_language"
case languageText = "language_text"
}
}
In your do catch
do the data
parse:
do {
let result = try JSONDecoder().decode([LanguageText].self, from: data)
} catch {
print("JSON error: \(error.localizedDescription)")
}
Upvotes: 1
Reputation: 275
You are trying to put id_language into a Int-Value, but in your JSON id_language is String.
Change id_language to String
struct LanguageText: Decodable {
let id_language: String
let language_text: String
}
Or you have to edit your JSON-File
[{"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!"}]
For parsing JSON I can recommend this site
Upvotes: 2
Reputation: 636
Use this to get array from row data.
let dataArray = getArrayFromJsonString(rowData: data)
func getArrayFromJsonString(arrayString:String)-> [[String : Any]] {
do {
return try JSONSerialization.jsonObject(with:
arrayString.data(using:
String.Encoding.utf8, allowLossyConversion: false)!,
options:
JSONSerialization.ReadingOptions.allowFragments) as! [[String :
Any]]
} catch let error {
print("Error: \(error)")
return []
}
}
Upvotes: 0