json - Swift 4 Playground - 从 JSON 获取对象/结果

标签 json swift swift4 swift-playground

我在 Playgrounds (MacOS) 中使用 Swift 4,作为初学者测试我的代码...我想从远程 JSON 获取标题的对象/结果。

代码一直运行到“print(object.title)”点,我希望它能返回导入的 JSON 中第一个标题的值。



    import Foundation
    import PlaygroundSupport

    PlaygroundPage.current.needsIndefiniteExecution = true

    // Create structer of Post
    struct Post: Codable {
        var userId: Int
        var title: String
        var body: String
    }

    // Remote JSON to Structed Object
    let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
    let jsonData = try! Data(contentsOf: url)
    let datastring = String(data: jsonData, encoding: .utf8)
    let decoder = JSONDecoder()

    do {
        // Decode data to object
        let object = try decoder.decode(Post.self, from: jsonData)
        print(object.title) 
    }
    catch {
        // Error Catch
        //print(error)
    }


最佳答案

此外,请注意 Swift4 的所有功能。我指的是 Swift 4 中的编码、解码和序列化。因此,您可以使用它。我为 Playground 添加了代码:

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

typealias JSONModel = [JSONModelElement]

class JSONModelElement: Codable {
    let userID, id: Int?
    let title, body: String?

    enum CodingKeys: String, CodingKey {
        case userID = "userId"
        case id, title, body
    }
}

let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
let jsonData = try! Data(contentsOf: url)

if let jsonModel = try? JSONDecoder().decode(JSONModel.self, from: jsonData) {
    for element in jsonModel {
        print(element.title)
    }
}

编码愉快!

关于json - Swift 4 Playground - 从 JSON 获取对象/结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49449439/

相关文章:

javascript - 如何检查数据是否被推送到 JSON 中

swift - 在 Swift 4 中使用 Decodable 和继承

json - Play2 找不到我的 JSON 隐式读取或格式

javascript - 迭代 JSON 对象

json - 使用电源查询转换 json(在单列中混合列表和记录)

arrays - 按对象 INT 快速过滤对象数组!属性(property)

ios - 无法以编程方式从 Controller 转到 View Controller

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

swift - KVC 和关联类型

ios - 从 Swift 2.3 (xCode 7) 迁移 --> Swift 4(xCode 9) + 更新 Cocoapods