使用 Codable 解析 JSON 数据

Posted

技术标签:

【中文标题】使用 Codable 解析 JSON 数据【英文标题】:Parsing the JSON data with Codable 【发布时间】:2018-07-31 21:03:52 【问题描述】:

我在可编码模型的帮助下解析了一个 JSON 响应。尽管我的模型看起来不错,但我收到以下错误,

失败:typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: “data”, intValue: nil)

JSON 响应是:


    "status": "success",
    "message": "successfully.",
    "user": 
        "username": "admin",
        "profileImage": "/storage/default.png"
    ,
    "data": 
        "cash": 
            "withdrawableCash": "$99999910",
            "outstandingOrders": "$0"
        ,
        "offering": [
            
                "company": "TSLA",
                "location": "Location",
                "amount": 40
            ,
            
                "company": "TSLA",
                "location": "Location",
                "amount": 50
            
        ],
        "history": [
            
                "amount": 100000000,
                "order_id": 0,
                "order_type": "deposit",
                "status": 1,
                "message": "Added money into wallet",
                "transaction_time": "30-07-2018 18:10"
            ,
            
                "amount": 40,
                "order_id": 1,
                "order_type": "auctionBid",
                "status": 2,
                "message": "Placed bid with 4 notes, on Auction (TSLA)",
                "transaction_time": "30-07-2018 18:11"
            ,
            
                "amount": 50,
                "order_id": 2,
                "order_type": "auctionBid",
                "status": 2,
                "message": "Placed bid with 5 notes, on Auction (TSLA)",
                "transaction_time": "30-07-2018 18:11"
            
        ]
    

模型是:

public struct WalletResponseModel: Codable 
    public let status: String
    public let message: String
    public let user: UserData
    public let data: WalletData


public struct UserData: Codable 
    public let username: String
    public let profileImage: URL

    enum CodingKeys: String, CodingKey 
        case username
        case profileImage = "profileImage"
    


public struct WalletData: Codable 
    public let cash: Cash
    public let history: [HistoryItem]
    public let offerings: [Offering]

    enum CodingKeys: String, CodingKey 
        case cash
        case history
        case offerings = "offering"
    


public struct Cash: Codable 
    public let withdrawableCash: String
    public let outstandingOrders: String


public struct HistoryItem: Codable 
    public let amount: Int
    public let status: Int
    public let orderId: Int
    public let orderType: String
    public let message: String
    public let transactionTime: String

    enum CodingKeys: String, CodingKey 
        case amount, status, message
        case transactionTime = "transaction_time"
        case orderId = "order_id"
        case orderType = "order_type"
    


public struct Offering: Codable 
    public let company: String
    public let amount: Int
    public let location: String

【问题讨论】:

显示您尝试解码 JSON 的代码。 Edit 你的问题。不要在 cmets 中发布代码。 请让我知道我应该发布什么。我需要尽快解决这个问题。 我已经告诉过你要发什么了。您已经尝试发布它。只需将代码放在问题中,而不是 cmets。 【参考方案1】:

我没有看到错误。但是以前当我遇到类似的问题时,我从一只小手开始,里面装满了数据和模型中的元素并进行了测试。一次添加一两个,直到发生错误并且可以找到问题。

【讨论】:

【参考方案2】:

试着像这样创作

struct Result:Decodable 
    let status: String
    let message: String
    let user:user
    let data: data


struct user:Decodable 
    let username: String
    let profileImage:String

struct data:Decodable 
    let cash:cash
    let offering:[offering]
    let history:[history]

struct cash:Decodable 
    let outstandingOrders:String
    let withdrawableCash: String

struct offering:Decodable 
    let location:String
    let company:String
    let amount:Int

struct history:Decodable 
    let amount: Int
    let message: String
    let orderId: Int
    let orderType: String
    let status:Int
    let transactionTime: String

并像

这样解码数据
do 
             let decoder = JSONDecoder()
            decoder.keyDecodingStrategy = .convertFromSnakeCase
            let response = try decoder.decode(Result.self, from: data)
            print(response)

         catch 
            // handle error
        

【讨论】:

以上是关于使用 Codable 解析 JSON 数据的主要内容,如果未能解决你的问题,请参考以下文章

使用 URLSession 和 Codable 解析 JSON 数据

使用 Codable 解析 JSON 数据

使用 Codable 解析多级 JSON

如何在json中使用Codable解析数据有键但值与枚举不匹配

使用 Alamofire/Codable 解析 JSON 行

如何使用 Codable 和 Swift 解析这个嵌套的 JSON?