Search code examples
iosuitableviewswift3alamofireswifty-json

Assign SwiftyJSON object to a String Array


Im working on a project in swift 3 and to call web services I use AlamoreFire and SwiftyJASON (pods). The Format as Bellow

    APIManager.apiGet(serviceName:appURLs.mainBaseURL+appURLs.testingPureLight, parameters: params) { (json:JSON?, error:NSError?) in
            if error != nil{

                print("error:",error as Any)

            }

            print(json!)
}

Therefore, I'm getting a Json response with type of JSON, thus,I get the following structure as my response.

 { 
  "media": [ {
    "key" : "value" 
    "Objectarray"[
     { "Object1":"somevalue" 
          "key2":"somevalue"
          "key3":"somevalue"
     } 

     {"Object2":"somevalue"
         "key2":"somevalue"
         "key3":"somevalue"
     } 

     { "Object3":"somevalue" 
          "key2":"somevalue"
          "key3":"somevalue"
     }

    ] 
  } ]
 }

My requirement is to catch this "Objectarray" and assign it to a string array so I could use it to populate in my UITableVIew. How could I achieve this ?


Solution

  • You can get your Objectarray this way.

    var objects = [String]() 
    if let jsonResponse = json,
       let objectArray = jsonResponse["media"][0]["Objectarray"].arrayValue {
    
        for object in objectArray {
            let object1 = object["Object1"].stringValue
            objects.append(object1)
        }
    }