-1

I have a json like bellow:

object{2}
  status: 1
  result{3}
     cohorts[23]
     categories[158]
     languages[16]

And I am Decoder it like bellow:

struct ResultAPIJSON: Decodable {
    private enum RootCodingKeys: String, CodingKey {
        case result
    }

    private enum FeatureCohortsCodingKeys: String, CodingKey {
        case cohorts
    }


    var cohortsPropertiesArray = [CohortsProperties]()


        init(from decoder: Decoder) throws {
            let rootContainerCohorts = try decoder.container(keyedBy: RootCodingKeys.self)
            var featuresContainerCohorts = try rootContainerCohorts.nestedUnkeyedContainer(forKey: .result)
            let AAA = try featuresContainerCohorts.nestedContainer(keyedBy: FeatureCohortsCodingKeys.self)
            let BBB = try AAA.nestedUnkeyedContainer(forKey: .cohorts)
            while BBB.isAtEnd == false {

                let propertiesContainer = try featuresContainerCohorts.nestedContainer(keyedBy: FeatureCohortsCodingKeys.self)
                // Decodes a single quake from the data, and appends it to the array.
                let properties = try propertiesContainer.decode(CohortsProperties.self, forKey: .cohorts)
                cohortsPropertiesArray.append(properties)
            }
        }
}

But get me bellow error:

typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
jo jo
  • 1,758
  • 3
  • 20
  • 34
  • 2
    The error is pretty clear and even if you haven't included the actual decoding code and your json example isn't json I am convinced that the issue is that you are trying to decode using the ResultAPIJSON directly but you can't skip the top level and start lower down so you probably need something like [String: ResultAPIJSON].self instead or to create a top level struct for your json – Joakim Danielson Oct 22 '19 at 08:36

1 Answers1

-1

If this is your JSON

object{2}
  status: 1
  result{3}
     cohorts[23]
     categories[158]
     languages[16]

(or more likely, this:)

{
    "status": 1,
    "result": {
        "cohorts": 23,
        "categories": 158,
        "languages": 16
    }
}

then you need two structs:

struct object: Decodable {
   let status: Int
   let result: Result
}

struct Result: Decodable {
   let cohorts: Int
   let categories: Int
   let languages: Int
}
Michael Shulman
  • 643
  • 5
  • 6