合并和嵌套 JSON 个对象
Combine and nested JSON objects
我有以下型号:
struct Book: Codable, Identifiable {
var id: Int
var title: String
var author: String
}
struct BookWrapper: Codable {
var books: [Book]
}
和JSON:
{
"books": [
{
"id": 1,
"title": "Nineteen Eighty-Four: A Novel",
"author": "George Orwell"
}, {
"id": 2,
"title": "Animal Farm",
"author": "George Orwell"
}
],
"errMsg": null
}
我正在尝试使用 Combine 获取数据,但找不到绕过 books 数组的方法。在 flat 数据的情况下,我将使用以下内容:
func fetchBooks() {
URLSession.shared.dataTaskPublisher(for: url)
.map{ [=13=].data }
.decode(type: [Book].self, decoder: JSONDecoder())
.replaceError(with: [])
.eraseToAnyPublisher()
.receive(on: DispatchQueue.main)
.assign(to: &$books)
}
我试过用BookWrapper.self,但是没有意义。有什么优雅的方法可以解决吗?
您可以 map
BooksWrapper
的 books
属性 在到达您的 assign
之前:
func fetchBooks() {
URLSession.shared.dataTaskPublisher(for: url)
.map{ [=10=].data }
.decode(type: BookWrapper.self, decoder: JSONDecoder())
.replaceError(with: BookWrapper(books: [])) //<-- Here
.map { [=10=].books } //<-- Here
.receive(on: DispatchQueue.main)
.assign(to: &$books)
}
我有以下型号:
struct Book: Codable, Identifiable {
var id: Int
var title: String
var author: String
}
struct BookWrapper: Codable {
var books: [Book]
}
和JSON:
{
"books": [
{
"id": 1,
"title": "Nineteen Eighty-Four: A Novel",
"author": "George Orwell"
}, {
"id": 2,
"title": "Animal Farm",
"author": "George Orwell"
}
],
"errMsg": null
}
我正在尝试使用 Combine 获取数据,但找不到绕过 books 数组的方法。在 flat 数据的情况下,我将使用以下内容:
func fetchBooks() {
URLSession.shared.dataTaskPublisher(for: url)
.map{ [=13=].data }
.decode(type: [Book].self, decoder: JSONDecoder())
.replaceError(with: [])
.eraseToAnyPublisher()
.receive(on: DispatchQueue.main)
.assign(to: &$books)
}
我试过用BookWrapper.self,但是没有意义。有什么优雅的方法可以解决吗?
您可以 map
BooksWrapper
的 books
属性 在到达您的 assign
之前:
func fetchBooks() {
URLSession.shared.dataTaskPublisher(for: url)
.map{ [=10=].data }
.decode(type: BookWrapper.self, decoder: JSONDecoder())
.replaceError(with: BookWrapper(books: [])) //<-- Here
.map { [=10=].books } //<-- Here
.receive(on: DispatchQueue.main)
.assign(to: &$books)
}