Augusto Carmo
Augusto Carmo

Reputation: 4964

Parse a String (of array of strings) in JSON to an array of Strings in Swift

Does Swift provide a way to convert a raw String like this

"[\"John\",\"Anna\",\"Tom\"]"

to an Array of strings ([String])?

I've looked for a way to do it over StackOverflow, but in that specific way, I could not find an answer :/

Upvotes: 1

Views: 260

Answers (2)

Cœur
Cœur

Reputation: 38667

Code Different answer is probably a recommended way to do it nowadays (Swift 4+).

For reference, here is a classic way to do the same, compatible with older Swift versions:

let rawString = "[\"John\",\"Anna\",\"Tom\"]"
let jsonData = rawString.data(using: .utf8)!
let strings = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [String] ?? []

According to Itai Ferber, JSONDecoder uses JSONSerialization under the hood, so it should do pretty much the same as Code Different answer.

Upvotes: 0

Code Different
Code Different

Reputation: 93161

On Swift 4 and later, use JSONDecoder:

let rawString = "[\"John\",\"Anna\",\"Tom\"]"
let jsonData = rawString.data(using: .utf8)!
let strings = try JSONDecoder().decode([String].self, from: jsonData)

Upvotes: 4

Related Questions