Search code examples
iosjsonswiftalamofire

Swift 3 Parsing JSON nesting issue


I'm trying to parse some json data and I'm struggling to understand how to pull out and assign the nested values. I can manage the first level but when it comes any further I struggle.

I have an parseProductsData function which receives the data and works fine along with the first level of nesting. How can i parse nested Json array of [“Options”: "values”],[”variants”].

This is my Json.

{
  products: [
    {
      id: 8931647873,
      title: "A bug Life1123",
      body_html: "
Ban neckline
Printed front
Full sleeves
Straight hem
Printed back
100% khaddar shirt without embroidery
 
",
      vendor: "Sapphire",
      product_type: "Configurable Products",
      created_at: "2017-03-01T23:54:41+05:00",
      handle: "a-bug-life",
      updated_at: "2017-03-17T16:30:46+05:00",
      published_at: "2017-01-07T12:33:00+05:00",
      template_suffix: "",
      published_scope: "global",
      tags: "Khaddar, L, M, Women, XL, Yellow",
      variants: [...],
      options: [
        {
          id: 10702667329,
          product_id: 8931647873,
          name: "Size",
          position: 1,
          values: [
            "XXS",
            "S",
            "M",
            "L",
            "XL",
            "XXL"
          ]
        },
        {
          id: 10702667393,
          product_id: 8931647873,
          name: "Color",
          position: 2,
          values: [
            "Yellow"
          ]
        }
      ],
      images: [
        {
          id: 20808811009,
          product_id: 8931647873,
          position: 1,
          created_at: "2017-03-01T23:54:41+05:00",
          updated_at: "2017-03-01T23:54:41+05:00",
          src: "https://cdn.shopify.com/s/files/1/1814/9759/products/a_bugs_life.jpg?v=1488394481",
          variant_ids: []
        },
        {
          id: 20808811073,
          product_id: 8931647873,
          position: 2,
          created_at: "2017-03-01T23:54:41+05:00",
          updated_at: "2017-03-01T23:54:41+05:00",
          src: "https://cdn.shopify.com/s/files/1/1814/9759/products/a_bugs_life..jpg?v=1488394481",
          variant_ids: []
        },
        {
          id: 20808811137,
          product_id: 8931647873,
          position: 3,
          created_at: "2017-03-01T23:54:41+05:00",
          updated_at: "2017-03-01T23:54:41+05:00",
          src: "https://cdn.shopify.com/s/files/1/1814/9759/products/a_bugs_life.__2.jpg?v=1488394481",
          variant_ids: []
        }
      ],
      image: {...}
    },

func parseProductsData() {
    Alamofire.request(BASE_URL+"/admin/products.json").responseJSON { response in
        let result = response.result
        if let dict = result.value as? Dictionary<String, AnyObject> {
            if let list = dict["products"] as? [Dictionary<String, AnyObject>] {
                for i in 0..<list.count {
                    print(list[i])
                }
            }
        }
    }
}

Solution

  • All you have to do is to understand the hierarchy and data type so that you can typecast into correct format. Here your structure is mostly like array of Dictionaries, on your key "product" you will fetch an array of dict and store it into a variable say list. You can now iterate the list and fetch the dict. Then later from dict you can get the values on keys say "id", "title", "vendor" and typecast into string. And for keys like "options", "images", you again have to typecast it into array of dictionaries and the process goes on the same. Just understand the data type and typecast it in the given format.

    func parseProductsData() {
            Alamofire.request(BASE_URL+"/admin/products.json").responseJSON { response in
                let result = response.result
                if let dict = result.value as? Dictionary<String, AnyObject> {
                    if let list = dict["products"] as? [Dictionary<String, AnyObject>] {
                        for dict in 0..<list {
                            //Now if you want to fetch the value on key "Options", you can see that your list of product holds an array Of Dictionary
                            //so all you have to do is
    
                            let arrOFOptions = dict["options"] as? [Dictionary<String, AnyObject>]
    
                            //Same goes for variants
    
                            let arrOfVariants = dict["variants"] as? [Dictionary<String, AnyObject>]
                        }
                    }
                }
            }
        }