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

2019-03-02 18:23发布

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 :/

2条回答
走好不送
2楼-- · 2019-03-02 18:35

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.

查看更多
冷血范
3楼-- · 2019-03-02 18:42

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)
查看更多
登录 后发表回答