Search code examples
jsonswiftxcodeswift4alamofire

read JSON result as array of dictionary


how to parse following JSON result

{
        "AddedByName": "jhon",
        "ApproveAction": 0,
        "ApproveActionName": "",
        "photos": null,
        "Status": 0,

    },
    {
        "AddedByName": "mike",
        "ApproveAction": 0,
        "ApproveActionName": "",
        "photos": null,
        "Status": 0,
    },
    {
        "AddedByName": "someone",
        "ApproveAction": 0,
        "ApproveActionName": "",
        "photos": [
            {
                "Id": 53,
                "Serial": 1,
                "Url": "0afe88a3-76e1-4bac-a392-173040936300.jpg"
            }
        ],
        "Status": 0,
    }

how can i reach the "photos" array ?

I already declare local array of dictionary to hold the whole responses as following

    var myLocalArray = [[String:Any]]()

and fill it from the JSON response like this

                if let Json = response.result.value as? [String:Any] {

                if let ActionData = Json["ActionData"] as? [[String:Any]] {

                    self. myLocalArray = ActionData

                }
            }

and it works

but i couldn't reach the "photos" array please help


Solution

  • @swiftIos provided the answer with Decodable which is absolutely a better way to handle the situation.

    But with your current you can access the photos from self.myLocalArray:

    if let jsonData = response.result.value as? [String: Any] {
        if let actionData = jsonData["ActionData"] as? [[String:Any]] {
            self.myLocalArray = actionData
        }
    }
    

    Now you have array for actionData, so access the photos by extracting the actionData for particular index as self.myLocalArray[0]. In whole:

    let index = 0
    if self.myLocalArray.count > index {
        if let photoArrayIndex0 = self.myLocalArray[index]["photos"] as? [[String: Any]] {
            print(photoArrayIndex0)
        }
    }