-4

I have a JSON response like this from my API:

SUCCESS: {
data =     (
            {
        addressDescription = "";
        addressLine1 = "30 xxx Street";
        addressLine2 = xxx;
        addressLine3 = "";
        addressType = 1;
        city = Lagos;
        country = Nigeria;
        id = xxx;
        state = Lagos;
    },
            {
        addressDescription = "AAA";
        addressLine1 = "11 bbb Street,";
        addressLine2 = "Ikeja";
        addressLine3 = "";
        addressType = 1;
        city = Lagos;
        country = Nigeria;
        id = xxx;
        state = Lagos;
    }
);

My Swift code looks like this:

var productsArray = [AnyObject]()

Alamofire.request(URL).responseJSON {
        response in

        //printing response
        print(response)

        //getting the json value from the server
        let result = response.result

        if let dict = result.value as? Dictionary<String,AnyObject> {
            if let innerDict = dict["data"]{
                self.addyArray = innerDict as! [AnyObject]
            }
        }

    }

How do I get the individual fields (addressLine1, addressLine2, etc) in this array to show in my UIPickerView? Any help will be appreciated.

3 Answers3

0

You can get all keys from Dictionary using this.

self.addyArray.first.keys //return array of keys

or

self.addyArray[0].keys //return array of keys

Make sure that your array is not empty.

Jayesh Thanki
  • 2,037
  • 2
  • 23
  • 32
-1

Assuming you getting result properly as per the above mentioned json structure.

    guard let dictRes = result as? [String : Any] else {
        print("No data")
        return
    }

    guard let data = dictRes["data"] as? [Any] else {
        return
    }

    for value in data {
        let dictData = value as? [String : Any]
        print("addressDescription : \(dictData!["addressDescription"])")
        print("addressLine1 : \(dictData!["addressLine1"])")
        print("addressLine2 : \(dictData!["addressLine2"])")
        print("addressLine3 : \(dictData!["addressLine3"])")
    }
dahiya_boy
  • 9,298
  • 1
  • 30
  • 51
-1
Alamofire.request(URL).responseJSON {
        response in

        //printing response
        print(response)

        //getting the json value from the server
        let result = response.result

        if let dict = result.value as? Dictionary<String,AnyObject> {
            if let innerDict = dict["data"]{
               for val in 0..<innerDict.count { 
                let dic = innerDict as! [String, AnyObject]
                  for vals in dic {
                    print(vals)
                    productsArray.append(vals) 
                  } 
               }
            }
        }

    }
MRizwan33
  • 2,723
  • 6
  • 31
  • 42