LoginSignup
16
16

More than 5 years have passed since last update.

JSON文字列をDictionaryに変換する

Last updated at Posted at 2017-02-02

JSONに含まれるある項目が、暗号化されて更にBase64 EncodeされたJSON文字列ってことがあって、一旦Dictionaryとして扱いたかったので調べたメモ。

JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] くらいで出来るので、意外と簡単でした。
変換に失敗した際にエラーが投げられるので、利用する際は適切にハンドリングするようにしましょう。

let json = "{\"fuga\":\"aiueo\",\"foo\":999,\"user\":{\"name\":\"tenten0213\",\"age\":30}}"
let data = json.data(using: .utf8)!

do {
    let dic = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] // ["fuga": "aiueo", "user": ["name": "tenten0213", "age": 30], "foo": 999]
    dic?["fuga"] // "aiueo"
    let user = dic?["user"] as? [String: Any] // ["name": "tenten0213", "age": 30]
    user?["name"] as? String // "tenten0213"
    user?["age"] as? Int // 30
} catch {
    print(error.localizedDescription)
}

…実は、SwiftyJSONObjectMapperで出来ないか調べて結構時間を使ってしまったので反省:no_mouth:

16
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
16