Swift 5:解码嵌套 JSON

问题描述 投票:0回答:1

我在将一些 JSON 数据解码为结构时遇到了一些问题。我尝试过以下方法,但不起作用:

JSON:

{
    "submission_date": "2020-02-28T14:21:46.000+08:00",
    "status": "pending",
    "requestor": {
        "name": "Adam"
    },
    "claim_items": [
        {
            "date": "2020-02-20",
            "description": "TV",
            "currency": "MYR",
            "amount": "103.0",
            "amount_in_ringgit": "10.0"
        },
        {
            "date": "2020-02-20",
            "description": "Netflix",
            "currency": "MYR",
            "amount": "12.0",
            "amount_in_ringgit": "10.0"
        }
    ]
}

结构方法一:

struct ClaimDetail: Decodable {
    let submission_date: String
    let status: String
    let requestor: Requestor
    let claim_items: [ClaimItem]
}

struct Requestor: Decodable {
    let name: String
    
    init(json: [String:Any]) {
        name = json["name"] as? String ?? ""
    }
}

struct ClaimItem: Decodable {
    let date: String
    let description: String
    let currency: String
    let amount: String
    let amount_in_ringgit: String
    
    init(json: [String:Any]) {
        date = json["date"] as? String ?? ""
        description = json["description"] as? String ?? ""
        currency = json["currency"] as? String ?? ""
        amount = json["amount"] as? String ?? ""
        amount_in_ringgit = json["amount_in_ringgit"] as? String ?? ""
    }
}

结构方法2:

struct ClaimDetail: Decodable {
    let submission_date: String
    let status: String
    let requestor: Requestor
    let claim_items: [ClaimItem]
    
    struct Requestor: Decodable {
        let name: String
        
        init(json: [String:Any]) {
            name = json["name"] as? String ?? ""
        }
    }
    
    struct ClaimItem: Decodable {
        let date: String
        let description: String
        let currency: String
        let amount: String
        let amount_in_ringgit: String
        
        init(json: [String:Any]) {
            date = json["date"] as? String ?? ""
            description = json["description"] as? String ?? ""
            currency = json["currency"] as? String ?? ""
            amount = json["amount"] as? String ?? ""
            amount_in_ringgit = json["amount_in_ringgit"] as? String ?? ""
        }
    }
}

结构体方法3(来自https://app.quicktype.io/):

// MARK: - ClaimDetail
struct ClaimDetail: Codable {
    let submissionDate, status: String
    let requestor: Requestor
    let claimItems: [ClaimItem]

    enum CodingKeys: String, CodingKey {
        case submissionDate = "submission_date"
        case status, requestor
        case claimItems = "claim_items"
    }
}

// MARK: - ClaimItem
struct ClaimItem: Codable {
    let date, claimItemDescription, currency, amount: String
    let amountInRinggit: String

    enum CodingKeys: String, CodingKey {
        case date
        case claimItemDescription = "description"
        case currency, amount
        case amountInRinggit = "amount_in_ringgit"
    }
}

// MARK: - Requestor
struct Requestor: Codable {
    let name: String
}

URL 会话

URLSession.shared.dataTask(with: requestAPI) { [weak self] (data, response, error) in
    if let data = data {
        do {
            let json = try JSONDecoder().decode(ClaimDetail.self, from: data)
            print (json)
        } catch let error {
            print("Localized Error: \(error.localizedDescription)")
            print("Error: \(error)")
        }
    }
}.resume()

全部返回以下错误:

本地化错误:无法读取数据,因为格式不正确。

错误:dataCorrupted(Swift.DecodingError.Context(codingPath:[],debugDescription:“给定的数据不是有效的 JSON。”,underlyingError:可选(Error Domain=NSCocoaErrorDomain Code=3840“字符 0 周围的值无效。”UserInfo={ NSDebugDescription=字符 0 周围的值无效。})))

ios swift struct
1个回答
2
投票

解决方案:

我使用了结构体方法#1,这不是问题。问题在于我如何解码 URLSession 中的数据。由于某种原因,这有效:

URLSession.shared.dataTask(with: requestAPI) { [weak self] (data, response, error) in
    
    if let data = data {
    
        do {
            let dataString = String(data: data, encoding: .utf8)
            let jsondata = dataString?.data(using: .utf8)
            let result = try JSONDecoder().decode(ClaimDetail.self, from: jsondata!)
            print(result)
        
        } catch let error {
            print("Localized Error: \(error.localizedDescription)")
            print("Error: \(error)")
        }
    }
}.resume()

截图:

enter image description here

我不太明白,但我想我必须将数据转换为字符串,然后对其进行解码?

谢谢大家的帮助。

© www.soinside.com 2019 - 2024. All rights reserved.