无法解析 Swift Codable 的响应

Unable to parse response with Swift Codable

无法解码来自服务器的 json 响应可解码 提供帮助或建议将不胜感激

JSON: *

["error": <__NSArrayM 0x60400044ab60>(
)
, "data": <__NSArrayM 0x60400044fae0>(
{
    id = 0;
    name = all;
},
{
    id = 1;
    name = "MONTHLY SUPPLIES";
}
)
, "success": 1]

//响应在数组字典中

代码:

struct CategoryData: Decodable {

    var categories: [Category]! // Array
    //codable enum case 
    private enum DataKeys: String, CodingKey {
        case data
    }
    // Manually decode values
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: DataKeys.self)
        let data = try container.decode([[String: String]].self, forKey: .data)
        print(data)
        /* Category is a class here contains 2 variable name and id.*/
        categories = data.map({ Category([=12=]) })
        print(categories)

    }
}

请使您的 Category 结构符合 Codable。您还应该将 categories 映射到 "data".

//: Playground - noun: a place where people can play

import Foundation

struct CategoryData: Codable {

    let categories: [Category]

    private enum CodingKeys: String, CodingKey {
        case categories = "data"
    }
}

struct Category: Codable {

    let id: Int
    let name: String
}

// create json mock by encoding

let category1 = Category(id: 0, name: "all")
let category2 = Category(id: 1, name: "MONTHLY SUPPLIES")
let categoryData = CategoryData(categories: [category1, category2])
let json = try! JSONEncoder().encode(categoryData)

print(String(bytes: json, encoding: String.Encoding.utf8)) // Optional("{\"data\":[{\"id\":0,\"name\":\"all\"},{\"id\":1,\"name\":\"MONTHLY SUPPLIES\"}]}")

// create category data by decoding json (your actual question)

do {
    let categoryDataAgain = try JSONDecoder().decode(CategoryData.self, from: json)
    for category in categoryDataAgain.categories {
        print(category.id) // 0, 1
        print(category.name) // "all", "MONTLY SUPPLIES"
    }
} catch {
    print("something went wrong")
}