我在Playgrounds(MacOS)中使用Swift 4,作为初学者测试我的代码......我想从远程JSON获取标题的对象/结果。
代码正在运行,直到打印(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)
}
答案 0 :(得分: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)
}
}
快乐的编码!
答案 1 :(得分:0)
请(学习)阅读 JSON。根对象是一个数组(由[]
表示),因此您需要解码[Post]
和循环以打印所有项目:
let object = try decoder.decode([Post].self, from: jsonData)
for post in object {
print(post.title)
}
永远不会忽视错误
} catch {
print(error)
}