Yoohogyun
Yoohogyun

Reputation: 226

Alamofire + swiftyJSON array parsing

When I got JSON {"categories": "[\"a/b/c\",\"d\"]"} from server,

Then How can I parse it to ["a/b/c", "d"]

When I using .arrayValue, then it always return []

Upvotes: 0

Views: 575

Answers (2)

Rob
Rob

Reputation: 437402

You have an array represented as raw JSON string within your JSON. You have three options:

  1. Try to manually scan through replacing occurrences of \" (which you'll have to confusingly escape both the backslash character and the quotation mark encountered with a backslash when you write your code, e.g. "\\\"") before you parse the JSON. To do this, you'd probably use responseData rather than responseJSON, do your manual replacement of characters, and then manually parse it yourself with NSJSONSerialization. The downside here is that you might want to check for other escaped characters, too (e.g. what if the nested JSON was pretty printed, then you might have \n or even \t in there, too, which you'd want to convert as well).

  2. Manually run JSON parsing again for each of those values that contain a JSON string in the responseObject. If you're stuck with the existing JSON, I think this is probably safest.

    For example, if the raw json was really just:

    {"categories": "[\"a/b/c\",\"d\"]"} 
    

    Then you could do something like:

    Alamofire.request(request)
        .responseJSON { response in
            guard response.result.error == nil else {
                print(response.result.error!)
                return
            }
    
            do {
                if let dictionary = response.result.value as? [String: String],
                    let categoryData = dictionary["categories"]?.dataUsingEncoding(NSUTF8StringEncoding),
                    let categories = try NSJSONSerialization.JSONObjectWithData(categoryData, options: []) as? [String]
                {
                    let result = ["categories" : categories]
                    print(result)
                }
            } catch {
                print(error)
            }
    }
    

    Then the result would be:

    ["categories": ["a/b/c", "d"]]
    
  3. Fix the web service that's generating this JSON so that it's not doing this silliness. This is probably the best solution, though it will take some detective work to figure out why/how the web service put JSON inside JSON. I know that you say you can't change the server side, but you really should escalate this to someone on the server team to fix this. It's silly to write client code to work around some mistake (either a mistake in the server code itself, or how the server was provided the data in the first place).

Upvotes: 1

iamyogish
iamyogish

Reputation: 2432

First up, the response you're getting from the server is a String and not Array. Hence you'll get empty array when you do .arrayValue . If you want to convert the string into an array, first you need to remove the "[" & "]" and then you need to do the componentsSeparatedByString with string as "," for the resultant string. You can use the following code snippet to do that:

    let str = "[\"a/b/c\",\"d\"]"
    let filteredString = String (str.characters.filter { $0 != "[" && $0 != "]"})
    print(filteredString)
    let filteredStringArray = filteredString.componentsSeparatedByString(",")
    print(filteredStringArray)

HTH :)

Upvotes: 0

Related Questions