0

I am trying to access the JSON that I get via Alamofire:

func getDataFromServer() {
    Alamofire.request(.POST, websiteURL, parameters: myParameters) .responseString {
        (response) -> Void in
        if let value = response.result.value {
            let json = JSON(value)
            self.parseJSON(json)
        }
    }
}

,and the JSON that is being returned to me looks something like this:

{  
"status":"success",
"object":[  
  {  
     "name":"Bob",
     "age":"20 ",
  },
  {  
     "name": "Jane",
     "age":"25"
  },
]
}

and I am using SwiftyJSON to access the names:

func parseJSON(json: JSON) {
    for result in json["object"].arrayValue {
        print(result["name"].stringValue)
    }
}

but it is not printing anything. Am I doing something wrong?

manohjay
  • 110
  • 1
  • 9
  • The json format is not correct. Could this be the problem? The correct son format should be { "status": "success", "object": [ { "name": "Bob", "age": "20 " }, { "name": "Jane", "age": "25" } ] } – Pradeep K Feb 06 '16 at 17:34
  • I made a mistake typing out the JSON manually, but I managed to fix my problem. I was returning the data as an string instead of a JSON. – manohjay Feb 06 '16 at 17:43

4 Answers4

2

responseJSON should be used instead of responseString

Arthur Alves
  • 458
  • 1
  • 5
  • 13
0

Your JSON is invalid

{
  "status": "success",
  "object": [
    {
      "name": "Bob",
      "age": "20 ",

    },
    {
      "name": "Jane",
      "age": "25"
    }, <--Delete this comma

  ]
}
Daniel Krom
  • 9,751
  • 3
  • 43
  • 44
  • Opps, sorry. Was manually typing out the JSON. But the comma isn't there in the actual JSON, and the JSON is a valid JSON. – manohjay Feb 06 '16 at 17:32
  • @manohjay Ok, then the Almonfire doesn't return `NSData`, see here example http://stackoverflow.com/questions/32018741/how-to-get-the-result-value-of-alamofire-request-responsejson-in-swift-2 – Daniel Krom Feb 06 '16 at 17:35
  • I managed to fix my problem. I was returning the data as an string instead of a JSON. – manohjay Feb 06 '16 at 17:43
0

Managed to figure out what was wrong with my code. When I did a POST request using Alamofire, I was returning the data back as a string: .responseString instead of JSON: .responseJSON

working code:

func getDataFromServer() {
Alamofire.request(.POST, websiteURL, parameters: myParameters) .responseJSON {
    (response) -> Void in
    if let value = response.result.value {
        let json = JSON(value)
        self.parseJSON(json)
    }
}
}
manohjay
  • 110
  • 1
  • 9
0

Replace responseString with responseJSON

Pradeep K
  • 3,671
  • 1
  • 11
  • 15