【发布时间】:2019-08-09 06:25:32
【问题描述】:
我正在尝试解码 JSON 响应,但收到一条错误消息:
由于格式不正确,无法读取数据
响应位于["Product"] 节点中的数组中。我收到了回复,但我认为 ["PictureCollection"] 中的节点由于格式不正确而未正确解码。
这是 API 响应。一些 API 对象还不需要。只有我包含在 Product.swift 模型中的属性。
"RMessage" : "OK",
"RSuccess" : true,
"RValue" : null,
"InputKeyword" : “Soap”,
"ProductSearchMode" : 4,
"Product" : [
{
"MinPrice" : 2000,
"Gname" : “Soap Brand 1”,
"MaxPrice" : 3190,
"IconFlgList" : [
],
"SoldoutFlg" : null,
"PictureCollection" : {
"Count" : 1,
"URL" : [
"https:someURL.jpg"
]
},
"ProgramBroadcastDate" : null,
"ID" : 107,
"Icon2OffValue" : “555”,
"Gcode" : “3333”
},
{
"Gcode" : “3334”,
"IconFlgList" : [
],
"PictureCollection" : {
"Count" : 1,
"URL" : [
"https:https:someURL1.jpg"
]
},
"MaxPrice" : 2100,
"SoldoutFlg" : null,
"Icon2OffValue" : “551”,
"ProgramBroadcastDate" : null,
"ID" : 108,
"MinPrice" : 2001,
"Gname" : "Soap Brand 2”
这是我的代码:
struct Product: Codable {
var id : Int!
var gcode : String!
var gname : String!
var minPrice : Int!
var maxPrice : Int!
var pictureCollection : PictureCollection
enum CodingKeys : String, CodingKey {
case id = "ID"
case gcode = "GCode"
case gname = "Gname"
case minPrice = "MinPrice"
case maxPrice = "MaxPrice"
case pictureCollection = "PictureCollection"
}
struct PictureCollection : Codable {
var Count : Int!
var URL : String!
}
var product : Product!
var productArray = [Product]()
let jsonResult = JSON(data)
for json in jsonResult["Product"].arrayValue {
let jsonData = try json.rawData()
self.product = try JSONDecoder().decode(Product.self, from: jsonData)
self.productArray.append(self.product)
}
【问题讨论】:
-
你的问题很混乱。请花更多时间准备您的问题。没有名为
picture的元素。不清楚您要解码什么。 -
你不应该
try这样的方法。抓住DecodingError。它会准确地告诉你哪里出了问题。 -
@Desdenova 对不起,我把你弄糊涂了。底部有一个 catch 块,错误为“无法读取数据,因为它的格式不正确”
-
确保像
print(error)这样打印错误对象以获取完整的错误消息 -
发布一个有效的json,我会尽力帮助你。
标签: arrays json swift swifty-json jsondecoder