Reputation: 1445
Since yesterday when I updated xCode I'm receiving error in the console and I'm not getting my data from the API. I'm getting this error:
dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))
What I don't understand is that I never had any issues before and now I get this error out of nowhere, and I also don't know if the problem is server sided or in my swift code... Here if how I make the request:
// -- 1 -- Create an URL
if let url = URL(string: urlString){
// -- 2 -- Create a URLSession
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil{
print(error!)
return
}
if let safeData = data {
self.parseJSON(EventDatas: safeData)
}
}
task.resume()
}
}
func parseJSON(EventDatas: Data){
let decoder = JSONDecoder()
do{
let decodedData = try decoder.decode(LuxCategoryData.self, from: EventDatas)
var test: [Int] = []
for object in decodedData.category {
let category: CategoryData = CategoryData()
category.idCategory = object.idCategory
category.dtTitle = object.dtTitle
dropDown.optionArray.append(category.dtTitle)
test.append(Int(category.idCategory)!)
self.categoryData.append(category)
}
dropDown.optionIds = test
}catch{
print(error)
}
}
Here is the decodable struct I use to parse the JSON:
struct LuxCategoryData : Decodable {
let category: [Category]
}
struct Category: Decodable {
let idCategory: String;
let dtTitle: String;
}
This is how my JSON look like when I make a request in the browser:
{
category: [
{
idCategory: "1",
dtTitle: "Cinema"
},
{
idCategory: "2",
dtTitle: "Bar"
},
{
idCategory: "5",
dtTitle: "Danse"
},
{
idCategory: "6",
dtTitle: "Nightlife"
},
{
idCategory: "10",
dtTitle: "Music"
}
]
}
Upvotes: 3
Views: 11958
Reputation: 24341
The JSON you provided doesn't contain " "
around the keys. That's why it is giving invalid JSON error.
Try with the below JSON format,
{"category":[{"idCategory":"1","dtTitle":"Cinema"},{"idCategory":"2","dtTitle":"Bar"},{"idCategory":"5","dtTitle":"Danse"},{"idCategory":"6","dtTitle":"Nightlife"},{"idCategory":"10","dtTitle":"Music"}]}
Upvotes: 4
Reputation: 81
Error: Parse error on line 1:
{ category: [{ idCa
--^
Expecting 'STRING', '}', got 'undefined'
Upvotes: 2