无法使用可解码解码来自服务器的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($0) })
print(categories)
}
}
答案 0 :(得分:1)
Juse让您的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")
}