在swift中解析对象里面的json数组 [英] Parsing array of json inside object in swift

查看:120
本文介绍了在swift中解析对象里面的json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个示例 json 代码,我必须在我的项目中实现,
请告诉我如何编写代码。我多次写代码。它根本不起作用。所以我希望完整的例子。

It is a sample json code which I have to implemented in my project, please tell me how to write code. I wrote codes many times. It is not work at all. So I hope full example please.

在这里我可以看到,首先有一个对象,接下来有一个多个对象,最后是一个对象内的数组。请查看详细信息...

Here I can see, at first of all has a object, next has one multiple object, finally a array inside a object. Please see details...

    ActivityIndicator.customActivityIndicatory(self.view, startAnimate: true)

let url = URL(string: Configuration.BASE_URL+"/products/"+String(category_id)+"?page=1")  // sir


    //  let url = URL(string: Configuration.BASE_URL+"/products/"+String(category_id)) // sir


    URLSession.shared.dataTask(with:url!) { (urlContent, response, error) in
        if error != nil {
            print(error)
        }
        else {
            do {
                let json = try JSONSerialization.jsonObject(with: urlContent!) as! [String:Any]



                let items = json["products"] as? [[String: Any]] ?? []
                self.product_count = (json["product_count"] as? Int)!

                 self.arrProduct = [Product2]()

                      //print(json["products"])
                items.forEach { item in


                    let oProduc2 = Product2()

            //    oProduc2.current_page = items["current_page"] as! Int
                   // oProduc2.product_count = items["thumbnail_image_name"] as? String

                    let dataItems = item["data"] as? [String: Any]
                    print(dataItems?["data"])
                    let oProduct2Datas = Product2Data()

                    oProduct2Datas.name = dataItems?["name"] as? String
                   // oProduct2Datas.profileImageName = dataItems["profile_image_name"] as? String


                    oProduct2Datas.id = item["id"] as? Int
                    oProduct2Datas.name = item["name"] as? String
                    oProduct2Datas.image = item["image"] as? String
                    oProduct2Datas.ar_name = item["ar_name"] as? String
                    //oProduct2Datas.description = item["description"] as? String
                    //oProduct2Datas.ar_description = item["ar_description"] as? String
                    oProduct2Datas.price = item["price"] as! NSNumber
                    oProduct2Datas.quantity = item["quantity"] as? String
                    oProduct2Datas.is_featured = item["is_featured"] as? String
                    oProduct2Datas.seller_id = item["seller_id"] as? String
                    oProduct2Datas.payment_required = item["payment_required"] as? String
                    oProduct2Datas.is_editors_choice = item["is_editors_choice"] as? String
                    oProduct2Datas.created_at = item["created_at"] as? String
                    oProduct2Datas.updated_at = item["updated_at"] as? String

                    oProduc2.product2Datas = oProduct2Datas

                    self.arrProduct.append(oProduc2)




                   // self.arrProduct.append(oProduct)
                }

            } catch let error as NSError {
                print(error)
            }
        }

        //            print(self.arrProduct)

        DispatchQueue.main.async(execute: {
            ActivityIndicator.customActivityIndicatory(self.view, startAnimate: false)
            self.totalItemLabel.text = String(self.product_count) + " products"
            self.collectionView?.reloadData()
        })



        }.resume()

{

 "error": false,
  "product_count": 58,
  "products": {

    "total": 58,
    "per_page": 10,
    "current_page": 1,
    "last_page": 6,
    "next_page_url": "http:\/\/70doors.com\/mobile-app\/products\/21?page=2",
    "prev_page_url": null,
    "from": 1,
    "to": 10,
    "data": [
      {
        "id": 213,
        "category_id": 110,
        "name": "Test Product",
        "ar_name": "Test Product",
        "description": "this is a test product",
        "ar_description": "this is a test product",
        "price": 100,
        "quantity": 5,
        "is_featured": 0,
        "seller_id": 114,
        "payment_required": 100,
        "is_editors_choice": 0,
        "created_at": "2017-07-29 22:47:05",
        "updated_at": "2017-07-31 15:24:00",
        "image": "http:\/\/70doors.com\/uploads\/media\/1501357670images.jpg",
        "get_media": [
          {
            "id": 882,
            "product_id": 213,
            "title": "images.jpg",
            "file_name": "images.jpg",
            "file_in_disk": "1501357670images.jpg",
            "created_at": "2017-07-29 22:47:50",
            "updated_at": "2017-07-29 22:47:50"
          }
        ]
      },
      {
        "id": 210,
        "category_id": 98,
        "name": "mShop Combo of Yunteng YT-1288 Selfie Stick and 228 Mini Tripod - Black",

        "description": "Material : ABS resin material\r\nDurable and lightweight\r\nDesign : Wrist rope design\r\nEasy to carry\r\nSupported Models : Digital Camera and all iPhone and all Android phones\r\nMade of lightweight material for easy mobility",

        "price": 750,
        "quantity": 9,
        "is_featured": 0,
        "seller_id": 123,
        "payment_required": 10,
        "is_editors_choice": 0,
        "created_at": "2017-07-23 08:06:38",
        "updated_at": "2017-07-25 23:15:50",
        "image": "http:\/\/70doors.com\/uploads\/media\/15007864540.jpg",
        "get_media": [
          {
            "id": 875,
            "product_id": 210,
            "title": "0.jpg",
            "file_name": "0.jpg",
            "file_in_disk": "15007864540.jpg",
            "created_at": "2017-07-23 08:07:34",
            "updated_at": "2017-07-23 08:07:34"
          },
          {
            "id": 876,
            "product_id": 210,
            "title": "1.jpg",
            "file_name": "1.jpg",
            "file_in_disk": "15007864541.jpg",
            "created_at": "2017-07-23 08:07:34",
            "updated_at": "2017-07-23 08:07:34"
          },
          {
            "id": 877,
            "product_id": 210,
            "title": "2.jpg",
            "file_name": "2.jpg",
            "file_in_disk": "15007864542.jpg",
            "created_at": "2017-07-23 08:07:34",
            "updated_at": "2017-07-23 08:07:34"
          }
        ]
      },
      {
        "id": 209,
        "category_id": 98,
        "name": "mShop Locust Monopod Portable Pocket Selfie Stick - Black",

        "price": 125,
        "quantity": 10,
        "is_featured": 0,
        "seller_id": 123,
        "payment_required": 10,
        "is_editors_choice": 0,
        "created_at": "2017-07-23 08:04:41",
        "updated_at": "2017-07-23 08:04:41",
        "image": "http:\/\/70doors.com\/uploads\/media\/15007863250.jpg",
        "get_media": [
          {
            "id": 872,
            "product_id": 209,
            "title": "0.jpg",
            "file_name": "0.jpg",
            "file_in_disk": "15007863250.jpg",
            "created_at": "2017-07-23 08:05:25",
            "updated_at": "2017-07-23 08:05:25"
          },
          {
            "id": 873,
            "product_id": 209,
            "title": "1.jpg",
            "file_name": "1.jpg",
            "file_in_disk": "15007863251.jpg",
            "created_at": "2017-07-23 08:05:25",
            "updated_at": "2017-07-23 08:05:25"
          },
          {
            "id": 874,
            "product_id": 209,
            "title": "2.jpg",
            "file_name": "2.jpg",
            "file_in_disk": "15007863252.jpg",
            "created_at": "2017-07-23 08:05:25",
            "updated_at": "2017-07-23 08:05:25"
          }
        ]
      },
      {
        "id": 208,
        "category_id": 97,
        "name": "Huawei Full Cover Tempered Glass Screen Film Protector for P10 Plus - Black",

        "description": "Precise Screen Protector\r\nResidue Free\r\nDry Application\r\nProtects from Scratches\r\nSilicone Adhesive\r\nBubble Free",

        "price": 399,
        "quantity": 5,
        "is_featured": 0,
        "seller_id": 123,
        "payment_required": 10,
        "is_editors_choice": 0,
        "created_at": "2017-07-23 08:02:59",
        "updated_at": "2017-07-23 08:02:59",
        "image": "http:\/\/70doors.com\/uploads\/media\/15007862040.jpg",
        "get_media": [
          {
            "id": 871,
            "product_id": 208,
            "title": "0.jpg",
            "file_name": "0.jpg",
            "file_in_disk": "15007862040.jpg",
            "created_at": "2017-07-23 08:03:24",
            "updated_at": "2017-07-23 08:03:24"
          }
        ]
      },
      {
        "id": 207,
        "category_id": 96,
        "name": "Ldnio SC3604 3Power Socket 6USB Auto Max 3.4A - Grey",

        "price": 1500,
        "quantity": 6,
        "is_featured": 0,
        "seller_id": 123,
        "payment_required": 10,
        "is_editors_choice": 0,
        "created_at": "2017-07-23 07:58:59",
        "updated_at": "2017-07-26 22:55:09",
        "image": "http:\/\/70doors.com\/uploads\/media\/15007859860.jpg",
        "get_media": [
          {
            "id": 869,
            "product_id": 207,
            "title": "0.jpg",
            "file_name": "0.jpg",
            "file_in_disk": "15007859860.jpg",
            "created_at": "2017-07-23 07:59:46",
            "updated_at": "2017-07-23 07:59:46"
          },
          {
            "id": 870,
            "product_id": 207,
            "title": "1.jpg",
            "file_name": "1.jpg",
            "file_in_disk": "15007859861.jpg",
            "created_at": "2017-07-23 07:59:46",
            "updated_at": "2017-07-23 07:59:46"
          }
        ]
      },
      {
        "id": 206,
        "category_id": 96,
        "name": "Samsung Gear S2 Wireless Charging Dock - Black",

        "description": "Wirelessly charge the device\r\nSamsung Gear S2 \/ S2 Classic Smartwatch\r\nPower input: 5 V\r\nPower output: 5 V\r\nOutput current: 700 mA\r\nPower via your computer",

        "price": 2650,
        "quantity": 4,
        "is_featured": 0,
        "seller_id": 123,
        "payment_required": 10,
        "is_editors_choice": 0,
        "created_at": "2017-07-23 07:57:26",
        "updated_at": "2017-07-26 22:55:09",
        "image": "http:\/\/70doors.com\/uploads\/media\/15007858600.jpg",
        "get_media": [
          {
            "id": 868,
            "product_id": 206,
            "title": "0.jpg",
            "file_name": "0.jpg",
            "file_in_disk": "15007858600.jpg",
            "created_at": "2017-07-23 07:57:40",
            "updated_at": "2017-07-23 07:57:40"
          }
        ]
      },
      {
        "id": 205,
        "category_id": 96,

        "description": "Remax RP-U31\r\n3 USB Charger Plug\r\nInput: 100-200V~50\/60Hz\r\nOutput: 5V~2100mA\r\nPortable Power Adapter",

        "price": 800,
        "quantity": 10,
        "is_featured": 0,
        "seller_id": 123,
        "payment_required": 10,
        "is_editors_choice": 0,
        "created_at": "2017-07-23 07:55:36",
        "updated_at": "2017-07-23 07:55:36",
        "image": "http:\/\/70doors.com\/uploads\/media\/15007857590.jpg",
        "get_media": [
          {
            "id": 865,
            "product_id": 205,
            "title": "0.jpg",
            "file_name": "0.jpg",
            "file_in_disk": "15007857590.jpg",
            "created_at": "2017-07-23 07:55:59",
            "updated_at": "2017-07-23 07:55:59"
          },
          {
            "id": 866,
            "product_id": 205,
            "title": "1.jpg",
            "file_name": "1.jpg",
            "file_in_disk": "15007857591.jpg",
            "created_at": "2017-07-23 07:55:59",
            "updated_at": "2017-07-23 07:55:59"
          },
          {
            "id": 867,
            "product_id": 205,
            "title": "2.jpg",
            "file_name": "2.jpg",
            "file_in_disk": "15007857592.jpg",
            "created_at": "2017-07-23 07:55:59",
            "updated_at": "2017-07-23 07:55:59"
          }
        ]
      },
      {
        "id": 204,
        "category_id": 96,
        "name": "Samsung Samsung S8\/S8 Plus Fast Qi Wireless Charger",

        "description": "Perfect for at home or the office\r\nProvides wireless power whenever you set your device on the stand\r\nCompatible with Samsung S8 and S8 Plus\r\nOfficial Samsung Accessory",

        "price": 6999,
        "quantity": 3,
        "is_featured": 0,
        "seller_id": 123,
        "payment_required": 10,
        "is_editors_choice": 0,
        "created_at": "2017-07-23 07:53:23",
        "updated_at": "2017-07-25 23:15:50",
        "image": "http:\/\/70doors.com\/uploads\/media\/15007856230.jpg",
        "get_media": [
          {
            "id": 859,
            "product_id": 204,
            "title": "0.jpg",
            "file_name": "0.jpg",
            "file_in_disk": "15007856230.jpg",
            "created_at": "2017-07-23 07:53:43",
            "updated_at": "2017-07-23 07:53:43"
          },
          {
            "id": 860,
            "product_id": 204,
            "title": "1.jpg",
            "file_name": "1.jpg",
            "file_in_disk": "15007856231.jpg",
            "created_at": "2017-07-23 07:53:43",
            "updated_at": "2017-07-23 07:53:43"
          },
          {
            "id": 861,
            "product_id": 204,
            "title": "0.jpg",
            "file_name": "0.jpg",
            "file_in_disk": "15007856230.jpg",
            "created_at": "2017-07-23 07:53:43",
            "updated_at": "2017-07-23 07:53:43"
          },
          {
            "id": 862,
            "product_id": 204,
            "title": "1.jpg",
            "file_name": "1.jpg",
            "file_in_disk": "15007856231.jpg",
            "created_at": "2017-07-23 07:53:43",
            "updated_at": "2017-07-23 07:53:43"
          },
          {
            "id": 863,
            "product_id": 204,
            "title": "0.jpg",
            "file_name": "0.jpg",
            "file_in_disk": "15007856810.jpg",
            "created_at": "2017-07-23 07:54:41",
            "updated_at": "2017-07-23 07:54:41"
          },
          {
            "id": 864,
            "product_id": 204,
            "title": "1.jpg",
            "file_name": "1.jpg",
            "file_in_disk": "15007856811.jpg",
            "created_at": "2017-07-23 07:54:41",
            "updated_at": "2017-07-23 07:54:41"
          }
        ]
      },
      {
        "id": 203,
        "category_id": 112,
        "name": "Nikon D3300 DSLR 24.2MP 3\" With 18-55mm Is II Lens - Black",

        "description": "24.2MP DX-Format CMOS Sensor\r\nEXPEED 4 Image Processor\r\nNo Optical Low-Pass Filter\r\n3.0\" 921k-Dot LCD Monitor\r\nFull HD 1080p Video Recording at 60 fps\r\nMulti-CAM 1000 11-Point AF Sensor",

        "price": 40700,
        "quantity": 5,
        "is_featured": 0,
        "seller_id": 123,
        "payment_required": 10,
        "is_editors_choice": 0,
        "created_at": "2017-07-23 07:51:11",
        "updated_at": "2017-07-23 07:51:11",
        "image": "http:\/\/70doors.com\/uploads\/media\/15007854960.jpg",
        "get_media": [
          {
            "id": 856,
            "product_id": 203,
            "title": "0.jpg",
            "file_name": "0.jpg",
            "file_in_disk": "15007854960.jpg",
            "created_at": "2017-07-23 07:51:36",
            "updated_at": "2017-07-23 07:51:36"
          },
          {
            "id": 857,
            "product_id": 203,
            "title": "1.jpg",
            "file_name": "1.jpg",
            "file_in_disk": "15007854961.jpg",
            "created_at": "2017-07-23 07:51:36",
            "updated_at": "2017-07-23 07:51:36"
          },
          {
            "id": 858,
            "product_id": 203,
            "title": "2.jpg",
            "file_name": "2.jpg",
            "file_in_disk": "15007854962.jpg",
            "created_at": "2017-07-23 07:51:36",
            "updated_at": "2017-07-23 07:51:36"
          }
        ]
      },
      {
        "id": 202,
        "category_id": 112,
        "name": "Generic HD Action Camera 1080P With 2.0 Screen Wi-Fi Connection And Waterproof - Black",

        "description": "WiFi connectivity with iOS and Anroid App\r\nThe micro SD card slot can take up to a 32GB Micro SD HC card which at 720p on 30 frames per second can give over 3 hours recording time\r\nComes with 10 different mouting brackets\/clips\r\nNo need to have to buy each individual accessories or a case like some of the other major brands\r\n12.0MP CMOS sensor with high res wide-angle lens",

        "price": 8500,
        "quantity": 5,
        "is_featured": 0,
        "seller_id": 123,
        "payment_required": 10,
        "is_editors_choice": 0,
        "created_at": "2017-07-23 07:49:46",
        "updated_at": "2017-07-23 07:49:46",
        "image": "http:\/\/70doors.com\/uploads\/media\/15007854020.jpg",
        "get_media": [
          {
            "id": 855,
            "product_id": 202,
            "title": "0.jpg",
            "file_name": "0.jpg",
            "file_in_disk": "15007854020.jpg",
            "created_at": "2017-07-23 07:50:02",
            "updated_at": "2017-07-23 07:50:02"
          }
        ]
      }
    ]
  }
}


推荐答案

key products 的值是一个字典,而不是一个数组, guard 要退出的评估错误的范围:

The value for key products is a dictionary, not an array, guard the evaluation to exit the scope on an error:

guard let products = json["products"] as? [String: Any] else { return }

产品计数正确但删除括号并放入之后的感叹号为(我不知道为什么编译器会建议括号):

The product count is correct but remove the parentheses and put the exclamation mark after as (I have no idea why the compiler suggests the parentheses):

self.product_count = json["product_count"] as! Int

现在获取物品(再次带护卫):

Now get the items (again with a guard):

guard let items = products["data"] as? [[String:Any]] else { return }

并循环遍历

for item in items {
    let oProduct2Datas = Product2Data()

    oProduct2Datas.id = item["id"] as? Int
    oProduct2Datas.name = item["name"] as? String
...

这篇关于在swift中解析对象里面的json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆