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

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

@ferretdayo

SwiftyJSONでちょっと階層深くしたときのやり方

概要

与えられるJSONはこんな感じで,hobbiesの部分のデータ取得方法がわからなかった.
そこについて説明する.

{
    "users":[
        {
            "name": "太郎",
            "age": 23,
            "hobbies": [
                {
                    "id": 1,
                    "name": "野球"
                },
                {
                    "id": 5,
                    "name": "ダーツ"
                },
                {
                    "id": 20,
                    "name": "缶蹴り"
                }
            ]
        },
        .
        .
        .
    ]
}

実際のコード

Alamofire.request(requestUrl).responseJSON{ response in
    switch response.result {
        case .success(let value):
            let json = JSON(value)
            json["users"].forEach{(_, data) in
                let name = data["name"].string!
                let age = data["age"].int!

                let hobbyList = data["hobbies"].array
                hobbyList?.forEach{(data) in
                    let hobbyId = data["id"].int!
                    let hobbyName = data["name"].string!
                }
            }
        case .failure(let error):
            print("エラーだよー")
    }
}

こんな感じで取得することが出来ます.

let hobbyList = data["hobbies"].array
ここが対象のところで,.arrayとすることで,jsonの"hobbies"のデータを取得しています.

.arrayObjectもあるのですが,"hobbies"の中身をオブジェクトに変換してしまい?:のところが=になり,上手く出来ませんでした.

.arrayの場合
{
    "id": 1,
    "name": "野球"
}
.arrayObjectの場合
{
    "id" = 1,
    "name" = "野球"
}
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
2
Help us understand the problem. What are the problem?