JSON解码错误-typeMissmatch Swift 4
我正在尝试从JSON解析一些数据,我已经用另一个API得到了这些数据,但现在我有了另一个结构,我得到了类型错误匹配错误 JSON看起来像:JSON解码错误-typeMissmatch Swift 4,json,swift,swift4,codable,decodable,Json,Swift,Swift4,Codable,Decodable,我正在尝试从JSON解析一些数据,我已经用另一个API得到了这些数据,但现在我有了另一个结构,我得到了类型错误匹配错误 JSON看起来像: { "status": 200, "data": { "date": "2018-04-07T00:00:00.508Z", "featured": [ { "id": "2345", "name": "name", "price": "1,000", "priceIcon": "String", "priceIc
{
"status": 200,
"data": {
"date": "2018-04-07T00:00:00.508Z",
"featured": [
{
"id": "2345",
"name": "name",
"price": "1,000",
"priceIcon": "String",
"priceIconLink": "URLString",
"images": {
"icon": "URLString",
"png": "URLString",
"gallery": "URLString",
"featured": "URLString"
},
"rarity": "1String",
"type": "1String",
"readableType": "1String"
}
],
"daily": [
{
"id": "12324",
"name": "name",
"price": "1,500",
"priceIcon": "String",
"priceIconLink": "URLString",
"images": {
"icon": "URLString",
"png": "URLString",
"gallery": "URLString",
"featured": "URLString"
},
"rarity": "1String",
"type": "1String",
"readableType": "1String"
}
]
}}
和这样的可编码结构:
struct Base : Codable {
let status : Int
let data : DataItems
}
struct DataItems : Codable {
let date : String
let featured : [Featured]
let daily : [Daily]
}
struct Featured : Codable {
let id : String
let name : String
let price : String
let priceIcon : String
let priceIconLink : String
let images : Images
let rarity : String
let type : String
let readableType : String
}
struct Daily : Codable {
let id : String
let name : String
let price : String
let priceIcon : String
let priceIconLink : String
let images : Images
let rarity : String
let type : String
let readableType : String
}
struct Images : Codable {
let icon : String
let png : String
let gallery : String
let featured : String
}
但是当我尝试解码Json时,我得到了一个“Swift.DecodingError.typeMismatch”错误:
我的JSON解码器:
enum Result<Value> {
case success(Value)
case failure(Error)
}
func getItems(for userId: Int, completion: ((Result<Base>) -> Void)?) {
var urlComponents = URLComponents()
urlComponents.scheme = "https"
urlComponents.host = "api.jsonbin.io"
urlComponents.path = "/myurl"
let userIdItem = URLQueryItem(name: "userId", value: "\(userId)")
urlComponents.queryItems = [userIdItem]
guard let url = urlComponents.url else { fatalError("Could not create URL from components") }
var request = URLRequest(url: url)
request.httpMethod = "GET"
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = [
"secret-key": "xyz"
]
let session = URLSession(configuration: config)
let task = session.dataTask(with: request) { (responseData, response, responseError) in
DispatchQueue.main.async {
if let error = responseError {
completion?(.failure(error))
} else if let jsonDataTest = responseData {
// Now we have jsonData, Data representation of the JSON returned to us
// from our URLRequest...
// Create an instance of JSONDecoder to decode the JSON data to our
// Codable struct
let decoder = JSONDecoder()
do {
// We would use Post.self for JSON representing a single Post
// object, and [Post].self for JSON representing an array of
// Post objects
let posts = try decoder.decode(Base.self, from: jsonDataTest)
completion?(.success(posts))
} catch {
completion?(.failure(error))
}
} else {
let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : "Data was not retrieved from request"]) as Error
completion?(.failure(error))
}
}
}
task.resume()
}
var base:Base?
func loadJson() {
getItems(for: 1) { (result) in
switch result {
case .success(let base):
self.base = base
dump(base)
case .failure(let error):
fatalError("error: \(error.localizedDescription)")
}
}
}
枚举结果{
案例成功(价值)
案例失败(错误)
}
func getItems(对于userId:Int,completion:((结果)->Void)?){
var urlComponents=urlComponents()
urlComponents.scheme=“https”
urlComponents.host=“api.jsonbin.io”
urlComponents.path=“/myurl”
让userIdItem=URLQueryItem(名称:“userId”,值:“\(userId)”)
urlComponents.queryItems=[userIdItem]
guard let url=urlComponents.url else{fatalError(“无法从组件创建url”)}
var-request=URLRequest(url:url)
request.httpMethod=“GET”
让config=URLSessionConfiguration.default
config.httpAdditionalHeaders=[
“密钥”:“xyz”
]
let session=URLSession(配置:config)
让task=session.dataTask(带:request){(responseData,response,responseError)在
DispatchQueue.main.async{
如果let error=responseError{
完成?(.失败(错误))
}否则,如果让jsonDataTest=responseData{
//现在我们有了jsonData,返回给我们的JSON的数据表示
//根据我们的要求。。。
//创建一个JSONDecoder实例,将JSON数据解码到
//可编码结构
let decoder=JSONDecoder()
做{
//我们将使用Post.self作为表示单个Post的JSON
//对象和[Post].self,用于表示
//Post对象
let posts=try decoder.decode(Base.self,from:jsonDataTest)
完成?(.成功(职位))
}抓住{
完成?(.失败(错误))
}
}否则{
let error=NSError(域:“”,代码:0,用户信息:[NSLocalizedDescriptionKey:“未从请求”]检索数据)作为错误
完成?(.失败(错误))
}
}
}
task.resume()
}
var-base:base?
func loadJson(){
getItems(for:1){(result)in
切换结果{
案例。成功(让我们来看看):
self.base=base
卸载(基础)
案例。失败(let错误):
fatalError(“错误:\(error.localizedDescription)”)
}
}
}
我是swift新手,不知道这个错误告诉了我什么,也不知道“解码字符串但找到一个数字”的问题在哪里。我想我有点不对劲。。我希望有人能在那里帮助我 请显示要将数据解析为json的代码
let urlString = "your_url.json"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
do {
//Decode retrived data with JSONDecoder and assing type of Article object
let baseData = try JSONDecoder().decode(Base.self, from: data)
print(baseData) //whole project
print(baseData.status) //200.0
print(baseData.data.date)
for day in baseData.data.daily {
print(day.id)
print(day.images.icon)
print(day.images.featured)
print(day.images.gallery)
print(day.images.png)
print(day.name)
print(day.price)
print(day.priceIcon)
print(day.priceIconLink)
print(day.rarity)
print(day.readableType)
print(day.type)
}
for feature in baseData.data.featured {
print(feature.id)
print(feature.images.icon)
print(feature.images.featured)
print(feature.images.gallery)
print(feature.images.png)
print(feature.name)
print(feature.price)
print(feature.priceIcon)
print(feature.priceIconLink)
print(feature.rarity)
print(feature.readableType)
print(feature.type)
}
} catch let jsonError {
print(jsonError)
}
}.resume()
我试过这个,它对我有效
顺便说一句,我有点困惑,Featured
和Daily
都有相同的变量,但模型不同
编辑
您在问题中发布的数据是有效的。来自的json错误或不一致
在
每日
中有“特色”:false
,在特色
中它是一个字符串
。结构中应包含字符串。所以你会得到一个不匹配。一旦您尝试解析字符串(有效),然后尝试将布尔值解析为字符串(错误) 这就是我想要得到的JSON。在我的问题中添加了解码器是的,我明白。我的代码就是这样做的。添加https://api.jsonbin.io/b/5acbd2dc214f9a2b84c6f167/1
到您的_url.json
,您将获得所有数据。请参阅我的编辑。你的json数据不同。我意识到我不需要特色部分。我不解析它,它可以。。。谢谢你的帮助,你帮了我很多!
let urlString = "your_url.json"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
do {
//Decode retrived data with JSONDecoder and assing type of Article object
let baseData = try JSONDecoder().decode(Base.self, from: data)
print(baseData) //whole project
print(baseData.status) //200.0
print(baseData.data.date)
for day in baseData.data.daily {
print(day.id)
print(day.images.icon)
print(day.images.featured)
print(day.images.gallery)
print(day.images.png)
print(day.name)
print(day.price)
print(day.priceIcon)
print(day.priceIconLink)
print(day.rarity)
print(day.readableType)
print(day.type)
}
for feature in baseData.data.featured {
print(feature.id)
print(feature.images.icon)
print(feature.images.featured)
print(feature.images.gallery)
print(feature.images.png)
print(feature.name)
print(feature.price)
print(feature.priceIcon)
print(feature.priceIconLink)
print(feature.rarity)
print(feature.readableType)
print(feature.type)
}
} catch let jsonError {
print(jsonError)
}
}.resume()