JSON decoding in Swift Failure

Just ran into this error when trying to decode some JSON in Swift and the error message had me stumped for too long despite being trivial so I thought I’d commit it to memory.

typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "bar", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))"

The JSON looked like this:

{
  "bar": 
  {
    "f1":"value1",
    "f2":"value2"
  }
}

And here’s the Swift struct I was trying to use to decode it:

struct Bar: Codable {
  let f1: String
  let f2: String
}

struct Foo: Codable {
  let bar: [Bar]
}

The problem is in the declaration of bar in Foo, it is not an array of Bar, it is just a Bar. So the declaration should be:

Struct Bar: Codable {
  let f1: String
  let f2: String
}

struct Foo: Codable {
  let bar: Bar
}

Then this test case will work:

func testFooJSONDecode() throws {
  let fooJson = 
    """
    {
      "bar": 
       {
         "f1":"value1",
         "f2":"value2"
       }
    }
    """.data(using: .utf8)!
    let decoder = JSONDecoder()
    let foo = try decoder.decode(Foo.self, from: fooJson)
    XCTAssertEqual(foo.bar.f1, "value1")
}

Leave a Reply