JSON array of mixed types using JSONDecoder

I have JSON Structure
Code Block
[
{
name: "Boo",
title: "Hello Boo",
value: [
subject: 88
]
},
{
name: "Foo",
title: "Hello Foo",
}
]

for decoding Purpose i performed this

Code Block
struct Students: Decodable {
let name: String,
let title: String,
let value: ValueHeader
}
struct ValueHeader: Decodable {
let subject: Int?
}


     
Code Block
fileprivate func fetchTaskItems(completion: @escaping (Result<[Students], Error>) -> ()) {
guard let url = URL(string: jsonString) else { return }
     
URLSession.shared.dataTask(with: url) { (data, response,err) in
       
      if let err = err {
        completion(.failure(err))
        return
      }
       
      do {
        let taskItem = try JSONDecoder().decode([Students].self, from: data!)
        completion(.success(taskItem))
      } catch let jsonError {
        completion(.failure(jsonError))
      }
       
    }.resume()
     
  }


i get an error as
Code Block
valueNotFound(Swift.KeyedDecodingContainer<App.ValueHeader.(unknown context at $10fd991dc).CodingKeys>,


I tried giving an optional to subject still not working any idea how to deal with this type of JSON

Replies

Your JSON Structure is not a valid JSON.
Especially this part:
Code Block
[
subject: 88
]

In JSON, [ ] is a JSON array and cannot contain a element like subject: 88.
(More precisely, even in JSON object, that should be "subject": 88.)

I cannot reproduce the error valueNotFound with your JSON Structure and your code.
Please show the right structure of your JSON.