简体   繁体   English

使用 swift codable 时处理不可预测的 json 响应

[英]Handling unpredictable json response when working with swift codable

Sometimes my JSON response is like this有时我的 JSON 响应是这样的

  {
 "products": [
             {
          "pId": "3564225",
           "name": "Maxi Skirt",
           "slug": "maxi-skirt",
            "sku": "s-navy",
            "priority": 10,
            "images": [

      ]
    },
    {
      "pId": "299328304",
      "name": "Necklace Setjewellery",
      "slug": "american-diamond-necklace-setjewellery",
      "sku": "free-size-purple",
      "priority": 10,
      "images": [

      ]
    }],
    "total": 2
}   

And Sometimes it looks like this有时它看起来像这样

{
  "products": [

  ],
  "total": 0
}

Swift decoder throws following error when parsing empty array response解析空数组响应时,Swift 解码器抛出以下错误

"*Swift.DecodingError.Context(codingPath: [], debugDescription: 
"The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 
"JSON text did not start with array or object and option to allow fragments not set." 
UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}*"

How do I write a swift codable struct to handle multiple response JSON like these above?我如何编写一个快速的可编码结构来处理像上面这样的多响应 JSON?

PS: I can't change anything from server side. PS:我无法从服务器端更改任何内容。

Both JSON objects are valid and can be decoded into两个 JSON 对象都是有效的,可以解码为

struct Root: Decodable {
    let products : [Product]
    let total: Int
}

struct Product: Decodable {
    let pId, name, slug, sku : String
    let priority : Int
    let images : [Image]
}

struct Image: Decodable {
    let url : URL
}

As images is empty I just assume that there is an URL.由于images是空的,我只是假设有一个 URL。 Change it to the real property name(s) and type(s)将其更改为真实的财产名称和类型

Just refer the following link... https://medium.com/xcblog/painless-json-parsing-with-swift-codable-2c0beaeb21c1只需参考以下链接... https://medium.com/xcblog/painless-json-parsing-with-swift-codable-2c0beaeb21c1

You will get all the stuffs about your issues and more informations in order to decrease further issues and improve your code structure.您将获得有关您的问题的所有内容和更多信息,以减少进一步的问题并改进您的代码结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM