【问题标题】:Swift JSON Codable Type Missmatch Vice VersaSwift JSON 可编码类型不匹配反之亦然
【发布时间】:2020-05-09 17:06:35
【问题描述】:

我在解析可编码结构中的 JSON 时遇到问题。

我将发布 2 次不同的尝试,每次尝试都具有相反的行为。

尝试1:

var url = URL(string: "https://api.imgflip.com/get_memes")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
    guard let data = data else {
        print("Is NIL")
        return
    }
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let memeData = try! decoder.decode([Int: Generals].self, from: data)
    print(memeData)
}

task.resume()


struct Generals: Codable {
    let success: String
    let data: [Int: Memes]
}

struct Memes: Codable {
    let memes: [MemeDetail]
}

struct MemeDetail: Codable {

    let id: Int
    let name: String
    let url: URL
    let width: Int
    let height: Int
    let box_count: Int
}

这个给了我以下错误信息:

致命错误:“试试!”表达式意外引发错误:Swift.DecodingError.typeMismatch(Swift.Int, Swift.DecodingError.Context(codingPath: [_DictionaryCodingKey(stringValue: "data", intValue: nil)], debugDescription: "Expected Int key but found String key 相反.",underlyingError: nil)):文件networking.playground,第15行

Type Missmatch Expected Int 但找到 String。

如果我将解码器字典更改为字符串:

let memeData = try! decoder.decode([String: Generals].self, from: data)

我收到相反的错误消息:

[_JSONKey(stringValue: "success", intValue: nil)], debugDescription: "期望解码 Dictionary 但找到了一个数字。",底层错误: nil)): 文件networking.playground,第11行

谁能给我一个建议,我做错了什么或者我错过了什么?

在 JSON 响应之后:

{
    "success": true,
    "data": {
        "memes": [
            {
                "id": "112126428",
                "name": "Distracted Boyfriend",
                "url": "https://i.imgflip.com/1ur9b0.jpg",
                "width": 1200,
                "height": 800,
                "box_count": 3
            },
            {
                "id": "181913649",
                "name": "Drake Hotline Bling",
                "url": "https://i.imgflip.com/30b1gx.jpg",
                "width": 1200,
                "height": 1200,
                "box_count": 2
            },

提前致谢!

【问题讨论】:

  • let data: [Int: Memes]=> let data: Memes 那里没有“Int”键。

标签: json swift codable


【解决方案1】:

始终根据您的 API 响应创建可编码模型。在您的场景中,我认为您的模型将是这样的:

struct Generals: Codable {
    let success: Bool
    let data: Memes
}

struct Memes: Codable {
    let memes: [MemeDetail]
}

struct MemeDetail: Codable {

    let id: String?
    let name: String?
    let url: String?
    let width: Int?
    let height: Int?
    let box_count: Int?
}

在从数据中解码时,像这样解码。

let memeData = try! decoder.decode(Generals.self, from: data) 

【讨论】:

  • 抱歉第二条评论,但您介意告诉我您如何在 JSON 响应中看到哪个值实际上是一个 Int,哪个是一个字符串?谢谢!
  • 一般情况下,双引号(" ")标记内的 JSON 响应值是一个字符串,一个带有小数的数字的值可以是浮点数/双精度数。
猜你喜欢
  • 1970-01-01
  • 2019-11-09
  • 2021-04-05
  • 1970-01-01
  • 2012-06-13
  • 2020-07-08
  • 1970-01-01
  • 2018-06-09
相关资源
最近更新 更多