用Swift获取Json Element

时间:2016-02-23 05:03:16

标签: json swift

我在解析类似的视频标题时遇到了问题。 json中总会有1或2个类似的电影,所以我试图将这两个视频存储在两个独立的阵列中。

这是我的JSON示例:

 {
        "status": "ok",
        "status_message": "Query was successful",
        "data": {
            "limit": 20,
            "movies": [
                {
                    "id": 400,
                    "url": "www.google.com",
                    "title": "Battle for Skyark",
                    "year": 2016,
                    "rating": 2.8,
                    "runtime": 88,
                    "genres": [
                        "Action",
                        "Adventure",
                        "Family",
                        "Sci-Fi"
                    ],
                    "summary": "When a mysterious race of creatures takes over a desolate Earth, humanity must take refuge in SkyArk, the city in the sky. After the rebellion against a corrupt leadership fails, the wealthy doom the rebels' children to live on the ruins of the old Earth. The rebel leader's son, Rags, must lead his fellow exiles against the monsters in order to have a chance to return to SkyArk, but he soon finds that he has a much greater purpose in saving humanity.",
                    "language": "English",
                    "background_image": "background.jpg",
                    "state": "ok",
                    "similarvideos": [
                        {
                            "title": "The Long Road"
                        },
                        {
                            "title": "Boyhood"
                        }
                    ],
                    "date_uploaded": "2015-10-31 21:48:19",
                    "date_uploaded_unix": 1446342499
                }
            }
        }

我能够解析这样的摘要(以及其他元素):

var summarys = [String]()
self.summarys = json.valueForKeyPath("data.movies.summary") as! [String]

这就是我试图解析类似视频标题的方法,但它无效:

self.similarfirstmovies = json.valueForKeyPath("data.movies.similarvideos[0].title") as! [String]
self.similarsecondmovies = json.valueForKeyPath("data.movies.similarvideos[1].title") as! [String]

非常感谢所有帮助。

2 个答案:

答案 0 :(得分:1)

乍一看,你的json不正确,"movies": [是一个数组应该在某个地方']',但似乎没有。

similarvideos 是一个数组,因此首先将其解析为数组,如

         let movies = json.valueForKeyPath("data.movies.similarvideos")
         movies.forEach { movie in
            print(movie["title"])
        }

应该有用。

答案 1 :(得分:1)

您可以获得类似的视频:

var similarfirstmovie = json.valueForKeyPath("data.movies[0].similarvideos[0].title") as! String
var similarsecondmovie = json.valueForKeyPath("data.movies[0].similarvideos[1].title") as! String

你的错误是电影是阵列。首先你应该选择你想要的电影。然后你就可以看到那部电影的类似视频了。

但是如果你想直接从json获得所有类似的第一个电影和第二个电影。首先你应该在一个数组中获得电影对象然后你应该写一个谓词来达到所有类似的视频。