首页 文章

使用Swift解码/解析特定的JSON

提问于
浏览
0

我在使用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的结构?

2 回答

  • 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)
        }
    }
    
  • 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()! 部分)

    但上面的代码有效,希望能回答你的问题 .

相关问题