Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

概要

与えられる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" = "野球"
}
idom
自動車流通業界の常識を覆すビジネスに挑戦し、ITを活用して移動という手段に新たな価値を創出することをミッションとしています。
https://221616.com/idom/
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした