我在 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/