代码之家  ›  专栏  ›  技术社区  ›  mikro098

类型与可解码和对象不匹配

  •  -2
  • mikro098  · 技术社区  · 7 年前

    我在解析来自服务器的数据时遇到问题。我有一个JSON,它有一个对象数组,如下所示:

    {
        "items": [
            {
                "itemType": {
                    "id": 12,
                    "tagId": "FCHA78558D"
                },
                "parts": [
                    {
                        "partId": 52,
                        "manufacturer": "xxx"
                    },
                    {
                        "partId": 53,
                        "manufacturer": "xxx"
                    },
                    {
                        "partId": 54,
                        "manufacturer": "xxx"
                    }
                ],
                "description": "yyy"
            },
            {
                "itemType": {
                    "id": 13,
                    "tagId": "FCHA755158D"
                },
                "parts": [
                    {
                        "partId": 64,
                        "manufacturer": "xxx"
                    },
                    {
                        "partId": 65,
                        "manufacturer": "xxx"
                    }
                ],
                "description": "zzz"
            }
        ]
    }
    

    我只想获得这一个对象数组,所以我实现了这样的类:

    class User : Object, Decodable {
       var items = List<Equipment>()
    }
    

    在Alamofire中,我下载JSON,将其解析为数据,然后在do catch块中,我收到一个错误:

    let items = try JSONDecoder().decode(User.self, from: receivedValue)

    错误:

    ▿ DecodingError
      ▿ typeMismatch : 2 elements
        - .0 : Swift.Array<Any>
        ▿ .1 : Context
          ▿ codingPath : 2 elements
            - 0 : CodingKeys(stringValue: "items", intValue: nil)
            ▿ 1 : _JSONKey(stringValue: "Index 0", intValue: 0)
              - stringValue : "Index 0"
              ▿ intValue : Optional<Int>
                - some : 0
          - debugDescription : "Expected to decode Array<Any> but found a dictionary instead."
          - underlyingError : nil
    

    这很奇怪,因为它确实是一个对象数组。我尝试将items属性设置为String以查看结果,然后得到: - debugDescription : "Expected to decode String but found an array instead." 我有过几次这样的错误,但我总能找到解决办法。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Dávid Pásztor    6 年前

    我想你用的是 List 有条件符合 Decodable 从我的回答到你的 previous question .我不完全理解为什么它在这个特定的案例中不起作用,但我会调查的。

    在此之前,您可以通过手动实现 init(from decoder:Decoder) 作用

    class User : Object, Decodable {
        let items = List<Equipment>()
    
        private enum CodingKeys: String, CodingKey {
            case items
        }
        required convenience init(from decoder:Decoder) throws {
            self.init()
            let container = try decoder.container(keyedBy: CodingKeys.self)
            let itemsArray = try container.decode([Equipment].self, forKey: .items)
            self.items.append(objectsIn: itemsArray)
        }
    }
    
    推荐文章