空对象阻止JSON可解码器快速运行

时间:2019-02-20 10:48:50

标签: ios json swift decodable

是否有一种方法可以避免空对象,以确保可解码的JSON起作用?我已经附加了JSON图片。

import UIKit

struct SearchResultData: Decodable  {
    let server_response_time: Int
    let data: [SearchResultType]
    let success: Bool
}

struct SearchResultType: Decodable  {
    let group: String
    let data: [Movie]
}

struct Movie: Decodable {
    let title: String
}

enter image description here

运行该应用程序时出现此错误。

  

无法解码JSON:keyNotFound(CodingKeys(stringValue:“ title”,intValue:nil),Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“ data”,intValue:nil),_JSONKey(stringValue:“索引2“,intValue:2),CodingKeys(字符串值:”数据“,intValue:nil),_ JSONKey(stringValue:”索引0“,intValue:0)],debugDescription:”没有与键CodingKeys相关联的值(stringValue:\ “ title \”,intValue:零)(\“ title \”)。“,底层错误:nil))

2 个答案:

答案 0 :(得分:2)

  

:“没有与键CodingKeys相关联的值(stringValue:\“ title \”,intValue:nil)(\“ title \”)。“,底层错误:nil))

意味着title在某些部分是nil,所以做到

let title: String?

您可能还需要

let data: [SearchResultType?]

因为data键还包含一些空值

答案 1 :(得分:1)

只需将Item ID Product ID Description Instock List Price Totalcost Button --------------------------------------------------------------------------------------------------------------------------------- EST-1 FI-SW-01 Large Angelfish $16.50 Add to Cart EST-2 FI-SW-01 Small Angelfish $16.50 Add to Cart Description for Item ID is Large Angelfish Item ID is EST-1

中可能为零的类型更改为可选
structs
  

debugDescription:“与键CodingKeys(stringValue:\“ title \”,intValue:nil)(\“ title \”)。“,underlyingError:nil))相关联的值<-正如此行所说

相关问题