JSON
Swift

swiftでのJSONの扱い方

書いた理由

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"}]