在swift

时间:2017-08-02 07:04:28

标签: ios json swift

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

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

    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"
          }
        ]
      }
    ]
  }
}

2 个答案:

答案 0 :(得分:1)

products的值是字典,而不是数组,guard评估在错误时退出范围:

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

产品计数是正确的,但删除括号并在as之后加上感叹号(我不知道为什么编译器会建议使用括号):

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

现在拿到物品(再次带护卫):

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
...

答案 1 :(得分:0)

试试这个:

func demo()
{
let str  : String =  "urlString"
let url =  NSURL(string:str)
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(request)
    .responseString { response in
        switch (response.result) {
        case .Success(let JSON):
            let data = JSON.dataUsingEncoding(NSUTF8StringEncoding)!
            do {
                let responseString = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
                print(responseString!)
                self.prodName = []
                let dict = responseString!["products"] as! NSDictionary
 let arr = dict["data"] as NSArray
                for j in 0..<arr.count{
                    let dic = arr[j] as! NSMutableDictionary
                    self.prodName.addObject(dic.valueForKey("name")!)

                }
            } catch _ as NSError {
                //print(error)
            }
            break
        case .Failure:
            print("FAILURE")
            break
        }
}}