Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
10
Help us understand the problem. What is going on with this article?
@nasutaro211

swiftでのJSONの扱い方

More than 3 years have passed since last update.

書いた理由

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

10
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
nasutaro211
Twitter: https://twitter.com/nasupc xcodeとかRailsを使ってアプリを作ってる。 名古屋大学アプリ開発団体jack副代表(Twitter: https://twitter.com/jackapp_tmy)

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
10
Help us understand the problem. What is going on with this article?