Swift 4 JSON Parsing Int — что я делаю неправильно?

Проблема Swift 4 JSON Parsing Int. Все примеры, которые я видел, Int кодируется/декодируется из коробки. Кто-нибудь видит, что я делаю неправильно?

Спасибо!

JSON

let patientBundleEntry = """
{
"resourceType": "Bundle",
"id": "patientListBundle",
"type": "SearchSet",
"total": 123
}
"""

Классы

class BundleFHIR: Resource {
var entry:[BundleEntry]?
var total:Int?   // this is printing -> Optional(105553116787496) instead of 123
}


class Resource:Codable {

var resourceType:ResourceType?  // this is printing fine
}

Тест - мое утверждение о том, что всего 123, терпит неудачу, а необязательный - длинное число. Есть идеи, почему? Моя кодировка неверна, используя .utf8 ??

func testModelBundle(){

    let jsonDataEncoded:Data? = patientBundleEntry.data(using: .utf8)!

    guard let responseData = jsonDataEncoded else {
        print("Error: did not receive data")

    }


    do {
        let bundleDecoded = try JSONDecoder().decode(BundleFHIR.self, from: responseData)

        print("bundleDecoded.resourceType resource type \(bundleDecoded.resourceType )")  //THIS is right
        print("bundleDecoded.resourceType total \(bundleDecoded.total )")  THIS is wrong 

        assert(bundleDecoded.total == 123, "something is wrong")  // ***** <- this assert fails and it prints Optional(105553116787496) 


    } catch {
        print("error trying to convert data to JSON")

    }
}

person devjme    schedule 29.01.2018    source источник
comment
Это связано с наследованием. Я обновлю это ответом через несколько. Но это очень странно.   -  person devjme    schedule 29.01.2018


Ответы (2)


Сначала вам нужно декодировать, а затем проанализировать данные JSON.

Следуйте приведенному ниже коду:

struct Patient: Codable {
        var resourceType: String
        var id: String
        var type: String
        var total: Int
    }

let json = patientBundleEntry.data(using: .utf8)!

let decoder = JSONDecoder()
let patient = try! decoder.decode(Patient.self, from: json)

print(patient.total) // Prints - 123
person Mimu Saha Tishan    schedule 02.10.2018

Хорошо, было много проблем с моим кодом. В основном из-за того, что у меня не было codingKeys как частного, и поэтому я пытался переименовать его, потому что дерево наследования не могло различить их. Это заставило меня не реализовывать настоящий протокол. Не уверен, почему он работал наполовину... но вот мой окончательный код, и он отлично работает!

class BundleFHIR: Resource {
var entry:[BundleEntry]?
var total:Int?


override init() {
    super.init()
}

required init(from decoder: Decoder) throws {


    try super.init(from: decoder)

    let values = try decoder.container(keyedBy: CodingKeys.self)

    total = try values.decodeIfPresent(Int.self, forKey: .total)
    entry = try values.decodeIfPresent([BundleEntry].self, forKey: .entry)
}

private enum CodingKeys: String, CodingKey
{
    case total
    case entry
}

}

 class Resource:Codable {

var resourceType:ResourceType?
var id:String?

init(){

}

required init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)


    resourceType = try values.decode(ResourceType.self, forKey: .resourceType)
    id = try values.decode(String.self, forKey: .id)
}

private enum CodingKeys: String, CodingKey
{
    case resourceType
    case id
}
}
person devjme    schedule 30.01.2018