我在使用Swift 4解码这个JSON时遇到了很多麻烦。
{
"Items": [
{
"id": 1525680450507,
"animal": "bee",
"type": "insect",
"diet": [
"a",
"b",
"c"
]
}
],
"Count": 1,
"ScannedCount": 5
}
这是我尝试解码的地方
let decoder = JSONDecoder()
let data = try decoder.decode([Animal].self, from: data)
我创建了一个像这样的结构
struct Animal: Codable {
var id: Int
var animal: String
var type: String
var diet: [String]
}
let decoder = JSONDecoder()
let data = try decoder.decode(ItemsResponse.self, from: data)
这不起作用。我收到一条错误
"预计解码数组< \ Any>但是找到了一本字典。"
所以我想也许我需要这样的东西
struct ItemsResponse: Codable {
var Items: [Animal]
var Count: Int
var ScannedCount: Int
}
但这也不起作用。现在我得到
"预计解码数组< \ Any>但是找到了一个字符串/数据。"
如何创建一个解码此JSON的结构?
答案 0 :(得分:0)
let data = try decoder.decode([Animal].self, from: data)
[Animal].self
不正确你可以像这样使用它:
struct DataJson: Codable {
let items: [Item]
let count, scannedCount: Int
enum CodingKeys: String, CodingKey {
case items = "Items"
case count = "Count"
case scannedCount = "ScannedCount"
}
}
struct Item: Codable {
let id: Int
let animal, type: String
let diet: [String]
}
// MARK: Convenience initializers
extension DataJson {
init(data: Data) throws {
self = try JSONDecoder().decode(DataJson.self, from: data)
}
func jsonData() throws -> Data {
return try JSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
extension Item {
init(data: Data) throws {
self = try JSONDecoder().decode(Item.self, from: data)
}
func jsonData() throws -> Data {
return try JSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
答案 1 :(得分:0)
试试这个:
import Foundation
let json = """
{
"Items": [
{
"id": 1525680450507,
"animal": "bee",
"type": "insect",
"diet": [
"a",
"b",
"c"
]
}
],
"Count": 1,
"ScannedCount": 5
}
"""
struct Animal: Codable {
var id: Int
var animal: String
var type: String
var diet: [String]
}
struct ItemsResponse: Codable {
var Items: [Animal]
var Count: Int
var ScannedCount: Int
}
let data = try! JSONDecoder().decode(ItemsResponse.self, from: json.data(using: .utf8)!)
当然,您应该正确处理可能的失败(即不要执行try!
,并且不要强行解开json.data()!
部分)
但上面的代码有效,希望能回答你的问题。