Search code examples
iosjsonswift3alamofireswifty-json

Swift 3 alamofire swiftyjson subscript


I don't know why my code doesn't work, my result is always nil. I integrated alamofire and swiftyjson this is my code:

let urlString = "myurl"

let params: Parameters = [
    "accessProvider": AccessProvider,
    "inputToken": AccessToken
]


Alamofire.request(urlString, method: .post, parameters: params, encoding: URLEncoding.httpBody)
    .responseJSON { response in
        if let responseObject = response.result.value {
            print("JSON: \(responseObject)")

            let json = JSON(responseObject)

            let path: [JSONSubscriptType] = ["user","id"]
            let name = json[path].string
            print("AAAAA")
            print(name)
        }
}

I can read the first part of user but the second one with id is always nil. this is the response json:

{
  "responseCode": 0,
  "responseDescription": "OK",
  "user": "{"id":"MAIL",
        "nickname":"MYNAME",
        "level":"U",
        "status":"A",
        "sex":null,
        "ageGroup":null,
        "address":null,
        "latitude":null,
        "longitude":null,
        "creation_timestamp":"2017-05-10 18:40:21",
        "notification":"1",
        "last_login":"2017-05-11 18:32:07",
        "mobilePreference":null,
        "sport":null,
        "spot":null,
        "token":"LONGTOKENID"}"
}

Solution

  • Thank you vadian, i solved the question with your indication, if anyone have the same problem you can solve like this: //Initialize the first json:

    let json = JSON(responseObject)
    

    //Extract the second Json to String

    let path: [JSONSubscriptType] = ["user"]
    let name = json[path].string
    

    //Initialize the second json from string

    if let dataFromString = name?.data(using: .utf8, allowLossyConversion: false) 
    let jsonuser = JSON(data: dataFromString)
    

    //Access to the data

    Thank you all, Have nice day.