在Swift

时间:2018-07-20 16:02:12

标签: json swift decode

我对开发完全陌生。试图找到解决方案,但他们无济于事。我需要解码下一个JSON数据:

{
  "page": {
    "currentPage": 1,
    "batchSize": 400,
    "totalItems": "23"
  },
  "items": [
    {
      "id": "b435a598-421c-4812-a3a9-773c47864558",
      "firstname": "\u041d\u0410\u0422\u0410\u041b\u0406\u042f \u0412\u0406\u041a\u0422\u041e\u0420\u0406\u0412\u041d\u0410",
      "lastname": "\u0413\u0423\u041d\u042c\u041a\u041e",
      "placeOfWork": "\u0437\u0430\u0441\u0442\u0443\u043f\u043d\u0438\u043a \u0434\u0438\u0440\u0435\u043a\u0442\u043e\u0440\u0430-\u043d\u0430\u0447\u0430\u043b\u044c\u043d\u0438\u043a \u0432\u0456\u0434\u0434\u0456\u043b\u0443 \u0441\u043e\u0446\u0456\u0430\u043b\u044c\u043d\u043e\u0457 \u0440\u043e\u0431\u043e\u0442\u0438 ",
      "position": "",
      "linkPDF": "https://public.nazk.gov.ua/storage/documents/pdf/b/4/3/5/b435a598-421c-4812-a3a9-773c47864558.pdf"
    },
    ......
  ]
}

我尝试了以下代码:

struct Declarant: Codable {
    var id: String
    var firstname: String
    var lastname: String
    var placeOfWork: String
    var position: String
    var linkPDF: String

    enum CodingKeys: String, CodingKey {
        case id
        case firstname
        case lastname
        case placeOfWork
        case position
        case linkPDF
    }

    init(from decoder: Decoder) throws {
        let valueContainer = try decoder.container(keyedBy: CodingKeys.self)
        self.id = try valueContainer.decode(String.self, forKey: CodingKeys.id)
        self.firstname = try valueContainer.decode(String.self, forKey: CodingKeys.firstname)
        self.lastname = try valueContainer.decode(String.self, forKey: CodingKeys.lastname)
        self.placeOfWork = try valueContainer.decode(String.self, forKey: CodingKeys.placeOfWork)
        self.position = try valueContainer.decode(String.self, forKey: CodingKeys.position)
        self.linkPDF = try valueContainer.decode(String.self, forKey: CodingKeys.linkPDF)
    }
}

struct DeclarationInfo: Codable {
    let items: [Declarant]

    enum CodingKeys: String, CodingKey {
        case items
    }

    init(from decoder: Decoder) throws {
        let valueContainer = try decoder.container(keyedBy: CodingKeys.self)
        self.items = [try valueContainer.decode(Declarant.self, forKey: CodingKeys.items)]
    }
}

...

let dataTask = URLSession.shared.dataTask(with: url) {
    (data, response, error) in
    let jsonDecoder = JSONDecoder()
    print("Trying to decode data...")
    if let data = data, let declarationInfo = try? jsonDecoder.decode(DeclarationInfo.self, from: data) {
        completion(declarationInfo)
        print(declarationInfo)
    } else {
        print("Either no data was returned, or data was not properly decoded.")
        completion(nil)
    }
}

并获得

  

要么没有返回数据,要么没有正确解码数据。

哪里出了错?

1 个答案:

答案 0 :(得分:1)

self.items = [try valueContainer.decode(Declarant.self, forKey: CodingKeys.items)]

应该是

self.items = try valueContainer.decode( [ Declarant ].self, forKey: CodingKeys.items )

完整代码:

import UIKit

struct Declarant: Codable {
    var id: String
    var firstname: String
    var lastname: String
    var placeOfWork: String
    var position: String
    var linkPDF: String
}

struct DeclarationInfo: Codable {
    let items: [Declarant]
}

let json = """
    {   \"page\"    : {
            \"currentPage\" : 1
        ,   \"batchSize\"   : 400
        ,   \"totalItems\"  : "23"
        }
    ,   \"items\"   : [
            {   \"id\"          : "b435a598-421c-4812-a3a9-773c47864558 1"
            ,   \"firstname\"   : "The first name 1"
            ,   \"lastname\"    : "The last name 1"
            ,   \"placeOfWork\" : "The placeofWork 1"
            ,   \"position\"    : "The position 1"
            ,   \"linkPDF\"     : "https://public.nazk.gov.ua/storage/documents/pdf/b/4/3/5/b435a598-421c-4812-a3a9-773c47864558.pdf"
            }
        ,   {   \"id\"          : "b435a598-421c-4812-a3a9-773c47864558 2"
            ,   \"firstname\"   : "The first name 2"
            ,   \"lastname\"    : "The last name 2"
            ,   \"placeOfWork\" : "The placeofWork 2"
            ,   \"position\"    : "The position 2"
            ,   \"linkPDF\"     : "https://public.nazk.gov.ua/storage/documents/pdf/b/4/3/5/b435a598-421c-4812-a3a9-773c47864558.pdf"
            }
        ]
    }
"""

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let jsonDecoder = JSONDecoder()
        print("Trying to decode data...")
        if  let data = json.data(using: .utf8),
            let declarationInfo = try? jsonDecoder.decode(DeclarationInfo.self, from: data) {
            print(declarationInfo)
        } else {
            print("Either no data was returned, or data was not properly decoded.")
        }
    }
}

控制台结果

Trying to decode data...
DeclarationInfo(items: [Dec.Declarant(id: "b435a598-421c-4812-a3a9-773c47864558 1", firstname: "The first name
 1", lastname: "The last name 1", placeOfWork: "The placeofWork 1",
 position: "The position 1", linkPDF:
 "https://public.nazk.gov.ua/storage/documents/pdf/b/4/3/5/b435a598-421c-4812-a3a9-773c47864558.pdf"),
 Dec.Declarant(id: "b435a598-421c-4812-a3a9-773c47864558 2", firstname:
 "The first name 2", lastname: "The last name 2", placeOfWork: "The
 placeofWork 2", position: "The position 2", linkPDF:
 "https://public.nazk.gov.ua/storage/documents/pdf/b/4/3/5/b435a598-421c-4812-a3a9-773c47864558.pdf")])