【问题标题】:Swift 4 Playground - getting object/result from JSONSwift 4 Playground - 从 JSON 获取对象/结果
【发布时间】:2018-03-23 12:14:47
【问题描述】:

我在 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) }

【问题讨论】:

    标签: json swift swift4 swift-playground


    【解决方案1】:

    另外,请注意 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)
        }
    }
    

    编码愉快!

    【讨论】:

    • 谢谢 Vadim - 你的示例代码看起来很棒,我会玩 :)
    【解决方案2】:

    请(学习)阅读 JSON。根对象是一个数组(由[] 表示),因此您需要解码[Post] 和一个循环来打印所有项目:

    let object = try decoder.decode([Post].self, from: jsonData)
    for post in object {
        print(post.title) 
    }
    

    永远,永远,永远不要忽略错误

    } catch {
      print(error)
    }
    

    【讨论】:

    • 嗨 Vadian,感谢您的快速回答.... 添加您的代码会导致以下错误:游乐场执行失败:错误:MyPlayground.playground:16:14:错误:键入“发布” ' 不符合对象 { ^ 中用户的协议“序列”
    • 谢谢,错误只是在我测试时被注释掉了......但是是的,它会有错误处理......但我仍然有错误......
    • 再一次,你必须解码[Post],而不是Post。请注意括号。
    • Ahhhh 非常感谢你的明星,没有看到括号.....那行得通,非常感谢 Vadian :)
    猜你喜欢
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 2020-11-14
    • 1970-01-01
    • 2016-12-14
    相关资源
    最近更新 更多