1

尝试使用 Swift json 解码器解析 json 时出现类型不匹配错误。

我只是找不到正常解析它的方法。

错误:

typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath:
[CodingKeys(stringValue: "data", intValue: nil), 
CodingKeys(stringValue: "itemArr", intValue: nil), 
CodingKeys(stringValue: "price", intValue: nil)], debugDescription:
"Expected to decode String but found a number instead.",
underlyingError:
nil))

解码器代码:

 func getDealDetails(id : String ,completion : @escaping ()->())
{
    let jsonUrl = "https://androidtest.inmanage.com/api/1.0/android/getDeal_\(id).txt"
    guard let url = URL(string: jsonUrl) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, error) in

        guard let data = data else { return }

        do
        {
            let deal = try JSONDecoder().decode(ResultDetails.self, from: data)
            AppManager.shared.dealToShow = deal.data.itemArr

        }catch
        {
            print("There's an error: \(error)")
        }

        completion()

        }.resume()



}
}

和课程:

第一的:

class ResultDetails : Decodable
{
  let data : DataDetails

init(data : DataDetails) {
    self.data = data
}


}

第二:

class DataDetails : Decodable
{
 let itemArr: ItemArr

init(itemArr: ItemArr) {
    self.itemArr = itemArr
}
}

第三:

class ItemArr : Decodable
{
let id, title, price, description: String
let image: String
let optionsToShow: Int
let gps: Gps
let website, phone: String

  init(id: String, title: String, price: String, description: String,   image: String, optionsToShow: Int, gps: Gps, website: String, phone: String) {
    self.id = id
    self.title = title
    self.price = price
    self.description = description
    self.image = image
    self.optionsToShow = optionsToShow
    self.gps = gps
    self.website = website
    self.phone = phone
}

我想我在过去 6 小时内尝试了所有方法来修复它,请帮忙!

编辑:

我放错了三等舱。现在是正确的

4

2 回答 2

2

错误信息是错误的。根据 JSON 链接和你的类,它应该是

CodingKeys(stringValue: "price" , intValue: nil)], debugDescription: 预期解码 Int 但找到了字符串/数据。,

然而,它会告诉你究竟出了什么问题: key 的值price是 aString而不是 an Int

您必须仔细阅读 JSON。格式非常简单。例如双引号中的所有内容String都是,也不例外。


你的数据结构太复杂了。使用结构并删除初始化程序。顺便说一句,有一个错字ItemsArrvs.ItemArr并且没有 key orderNum

密钥image可以解码为 URL。这足够了

struct ResultDetails : Decodable {
    let data : DataDetails
}

struct DataDetails : Decodable {
    let itemArr: ItemArr
}

struct ItemArr : Decodable {
    let id, title: String
    let price: String
    let image: URL
    // let orderNum: Int
}

CodingKeys仅当您要映射键时才指定。在您的情况下,您甚至可以省略CodingKeys, 改为使用该convertFromSnakeCase策略。

decoder.keyDecodingStrategy = .convertFromSnakeCase
于 2018-05-11T16:34:44.640 回答
0

是的,你有一个错误

let price: Int 应该是let price: String因为它是 Json 中的字符串"price": "896" --> String

Int 的示例 "optionsToShow":1--> 这是 Int

这是您可以使用的完整代码

import Foundation
struct ResultDetails: Codable {
    let data: DataDetails
}

struct DataDetails: Codable {
    let itemArr: ItemArr
}

struct ItemArr: Codable {
    let id, title, price, description: String
    let image: String
    let optionsToShow: Int
    let gps: Gps
    let website, phone: String
}

struct Gps: Codable {
    let lat, lon: String
}
// MARK: Convenience initializers

extension ResultDetails {
    init(data: Data) throws {
        self = try JSONDecoder().decode(ResultDetails.self, from: data)
    }

    init(_ json: String, using encoding: String.Encoding = .utf8) throws {
        guard let data = json.data(using: encoding) else {
            throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
        }
        try self.init(data: data)
    }


    func jsonData() throws -> Data {
        return try JSONEncoder().encode(self)
    }

    func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
        return String(data: try self.jsonData(), encoding: encoding)
    }
}
于 2018-05-11T16:32:43.977 回答