Swift 5: декодирование, вложенное JSON - PullRequest
0 голосов
/ 06 марта 2020

У меня небольшие проблемы с декодированием некоторых 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 Method 1:

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 "

1 Ответ

0 голосов
/ 09 марта 2020

Решение:

Я использовал метод struct # 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

Я не очень понимаю, но я думаю, мне пришлось преобразовать данные в строку, а затем расшифровать их?

Спасибо всем за помощь.

...