json - 预计解码数组而是找到了一本字典。”
问题描述
当我尝试解析volumeInfo
. 我能够检索totalItems
,如果我在struct 中省略id
,但是当我在struct 中添加时,解析不会发生,我收到上述错误。etag
var volumeInfo: [VolumeInfo]?
Items
var volumeInfo: [VolumeInfo]?
Items
这是我的 JSON 响应数据:
{
"kind": "books#volumes",
"totalItems": 2361,
"items": [
{
"kind": "books#volume",
"id": "_eyJAAAAQBAJ",
"etag": "MJbx6HKC3B4",
"selfLink": "https://www.googleapis.com/books/v1/volumes/_eyJAAAAQBAJ",
"volumeInfo": {
"title": "A Quilting Life",
"subtitle": "Creating a Handmade Home",
"authors": [
"Sherri McConnell"
],
"publisher": "C&T Publishing Inc",
"publishedDate": "2013-02-12",
"description": "Bring the handmade tradition home with these charming quilts and home accessories. Inspired by a grandmother who loved to sew for her family, quilter and blogger Sherri McConnell gives traditional patterns like hexagons, stars, snowballs, and Dresden Plates a new look featuring fabrics by some of today’s most popular designers. 19 cozy projects include pillows, tote bags, table runners, and larger quilts—quick and easy designs that make great gifts.",
数据模型:
struct Book: Codable {
var totalItems:Int = 0
var items:[Items]?
}
struct Items: Codable {
var id: String?
var etag: String?
var volumeInfo: [VolumeInfo]?
}
struct VolumeInfo: Codable {
var authors: String?
var categories: String?
var description: String
var pageCount: Int?
var publishedDate: String?
var publisher: String?
var subtitle: String?
var title: String?
}
import UIKit
class ViewController: UIViewController {
let urlString = "https://www.googleapis.com/books/v1/volumes?q=quilting"
var items: [Items] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let url = URL(string: urlString)
guard url != nil else {
return
}
let session = URLSession.shared
let dataTask = session.dataTask(with: url!) { [self] (data, response, error) in
//check for errors
if error == nil && data != nil{
//parse json
let decorder = JSONDecoder()
do {
let bookInfo = try decorder.decode(Book.self, from: data!)
items = bookInfo.items!
print("Retrieved books are \(items)")
}
catch {
print("Error in json parcing\(error)")
}
}
}
//make api call
dataTask.resume()
}
}
解决方案
推荐阅读
- javascript - D3.js 图表中堆栈栏和线条上的标签
- python - Python 简单的反向传播无法按预期工作
- javascript - 如何将字符串与数组中对象的值进行比较
- javascript - 为什么我看不到它,那是什么二进制代码
- mysql - 在 WHERE IN 子查询中选择
- azure - 如何更改管道变量以在 Azure DevOps 的下一个构建中使用
- python - 我想将 res.partner 地址中的实际城市字段更改为 many2one 字段而不添加新字段
- pine-script - 图表上的计算值
- arrays - Flutter:在包含 Listview 的 Futurebuilder 中显示来自 JSON 的字符串数组
- python - 无法将关键字“id”解析为字段。选项有:完成、task_priority、text、user、user_id