JSON structure with Swift and Alamofire

2019-09-13 21:51发布

Following on from This question

I am trying to bring in the summary field but it has a further value. I have brought in the title and author as follows:

func parseData(JSONData : Data) {
    do {
        var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONstandard
        // print(readableJSON)

        if let posts = readableJSON["posts"] as? [JSONstandard] {
            for post in posts {
                let title = post["title"] as! String

                let author = post["author"] as! String

                let summary = post["summary"] as! String

                print(author)

                if let imageUrl = post["image"] as? String {
                    let mainImageURL = URL(string: imageUrl )
                    let mainImageData = NSData(contentsOf: mainImageURL!)
                    let mainImage = UIImage(data: mainImageData as! Data)

                    postsinput.append(postinput.init(mainImage: mainImage, name: title, author: author, summary: summary))
                }
            }
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }

    }

    catch {
        print(error)
    }
}

But if i try the summary that way a error is returned. Any help would be appreciated.

JSON STRUCTURE

{
    "posts" : [{
        "id": "000000",
        "url": "/content/interview2",
        "date": "2016-11-03 09:01:41",
        "modified": "2016-11-03 09:03:47",
        "title": "An interview",
        "image": "https://www.example.com/sites/default/files/oregood.jpeg",
        "summary": {
            "value": "<p>Latin text here</p>",
            "format": "filtered_html"
        }
    }]
}

1条回答
乱世女痞
2楼-- · 2019-09-13 22:17

From your previous question response, summary key contains the Dictionary so you can try like this.

guard let dic = post["summary"] as? [String: Any], let summary = dic["value"] as? String else {
    return
}
查看更多
登录 后发表回答