使用数组根对象在 Swift 中解析 JSON 数组
Posted
技术标签:
【中文标题】使用数组根对象在 Swift 中解析 JSON 数组【英文标题】:Parsing JSON array in Swift with array root object 【发布时间】:2020-10-26 18:50:28 【问题描述】:我正在尝试使用以下格式解析 json 数组:
["id":1,"date":1596827226.558827,"at":"@mrpit", "name":"Pitmen", "content":"This is the first post, There is a bunch of interesting information in here",
"id":2,"date":1596827234.901298, "at":"@mrben", "name":"Benman", "content":"This is the second post, pretend there is a bunch of scientific information in here.",
"id":3,"date":1596827268.411034, "at":"@mrgreen", "name":"The Green Machine", "content":"This is the thrid post, idk what you wanna pretend is here, maybe something political",
"id":4,"date":1596834988.94011, "at":"@mrman", "name":"The Man who Can", "content":"And finally we are at the forth post, there is tons going on here, maybe even something offensive."]
我很麻烦,因为根对象似乎是一个数组。
我试图使用类似的东西
struct DataSet: Decodable
let post: [SinglePost]
struct SinglePost: Decodable
let id: Int
let date: Double
let at: String
let name: String
let content: String
static func getPost(returnWith: @escaping (DataSet?, Bool)->())
let session = URLSession.shared
let decoder = JSONDecoder()
let uString = serverUrl
if let url = URL(string: serverUrl + "/post/")
let task = session.dataTask(with: url, completionHandler: data1, response, error in
if (error != nil)
returnWith(nil, false)
return
if let dataString = String(data: data1!, encoding: .utf8)
print(dataString)
do
let postSet = try decoder.decode(DataSet.self, from: Data(dataString.utf8))
returnWith(postSet, true)
catch let jsonError
print("Error Serializing JSON", jsonError)
returnWith(nil, false)
else
returnWith(nil, false)
)
task.resume()
但这不起作用。
这样做的最佳方法是什么。抱歉,我对 swift 很陌生,所以这可能有一个明显的答案。
【问题讨论】:
【参考方案1】:问题在于您试图解码字典而不是数组。
只是改变
let postSet = try decoder.decode(DataSet.self, from: Data(dataString.utf8))
到
let postSet = try decoder.decode([SinglePost].self, from: Data(dataString.utf8))
编辑/更新:
关于您的方法签名,只需将其更改为返回数组而不是 DataSet 结构,我将返回错误而不是 Bool:
static func getPost(completion: @escaping ([SinglePost]?, Error?) -> ())
let session = URLSession.shared
let decoder = JSONDecoder()
if let url = URL(string: serverUrl + "/post/")
let task = session.dataTask(with: url) data, response, error in
guard let data = data else
completion(nil, error)
return
do
completion(try decoder.decode([SinglePost].self, from: data), nil)
catch
print("Error Decoding JSON", error)
completion(nil, error)
task.resume()
用法:
getPost posts, error in
guard let posts = posts else
print(error ?? "")
for post in posts
print(post)
【讨论】:
那返回类型会改成什么? 只需将方法签名更改为static func getPost(returnWith: @escaping ([SinglePost]?, Bool)->())
顺便说一句,我会将completionHandler 名称从returnWith 更改为刚刚完成
非常感谢!
我试过了,但当时还不够长,哈哈以上是关于使用数组根对象在 Swift 中解析 JSON 数组的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 SwiftyJSON 在 Swift 中解析这个 JSON 对象?
JSON .count 数组在 Swift 4 中总是返回 0