SwiftyJSON - no access to JSON data

126 views Asked by At

I'm trying to parse server response produced by following code (api for rails app developed with grape)

  if user.persisted?
    return user.to_json
  else
    error!(user.errors.to_json, 400)
  end

When user submit wrong data i see following response from server:

{
    response = "{\"email\":[\"is invalid\"],\"password\":[\"is too short (minimum is 8 characters)\"]}";
    "response_type" = error;
}

I use on client side following code:

API.registerUser(email: emailTextField.text, password: passwordTextField.text, password_confirmation: passwordConfirmationTextField.text) {
    (data, error, statusCode) in

    var errorMessage: String

    if (data == nil && statusCode == nil) {
        errorMessage = "Server error. Please try again later"
    } else if (statusCode == 400) {
        var errors = JSON(data!)["response"]

        errorMessage = "Registration error: \n"

        // Display error notice with details

        errorMessage = errorMessage + errors.stringValue

        }

        NSLog(errorMessage)
}

In this code errors variable contains "{\"email\":[\"is invalid\"],\"password\":[\"is too short (minimum is 8 characters)\"]}" but i cannot use errors["email"] - it contains no data. How can i loop thru errors and access all data?

2

There are 2 answers

0
Alexey Poimtsev On BEST ANSWER

the problem was on a server side, because it generated escaped json. I've fixed it with following

error!(user.errors, 400)

It was my mistake :)

0
cjnevin On

Yeah, you need to parse the response key in order to read it as a dictionary. It also looks like you might have to unescape the response before you parse it unless your parser takes care of that for you.