LoginSignup
9
10

More than 5 years have passed since last update.

swiftでのJSONの扱い方

Last updated at Posted at 2018-03-08

書いた理由

JSONの扱い方が僕には複雑だったのでまとめ

JSONの扱い方

jsonPractice.swift
//Stringスタート
let initJSONStr = "[{\"question\":\"str\",\"answers\":[\"Str1\",\"Str2\"]},{\"question\":\"str\",\"answers\":[\"Str1\",\"Str2\"]}]"
//StringからDataへ
let data = initJSONStr.data(using: .utf8)!
//DataからJSONObjectへ
let json = try? JSONSerialization.jsonObject(with: data, options: [])
//JSONObjectからArrayへ
var array:Array<Dictionary<String,Any>> = []
//jsonの中身がちゃんとarrayにできるかを確認
if let checkArray = json as? [Dictionary<String,Any>]{
        array = checkArray
}
//arrayを適当に編集
array[0]["question"] = "aaa"
var newQuestion:Dictionary<String,Any> = ["question":"new","answers":["答え1","答え2"]]
array.append(newQuestion)
//ArrayからData
let data2 = try JSONSerialization.data(withJSONObject: array, options: [])
//DataからString
let jsonStr = String(bytes: data2, encoding: .utf8)!
print(jsonStr)//[{"question":"aaa","answers":["Str1","Str2"]},{"question":"str","answers":["Str1","Str2"]},{"answers":["答え1","答え2"],"question":"new"}]

9
10
2

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
9
10