Swift:帮助Json解析可编码/可解码

时间:2019-06-20 02:49:06

标签: swift xcode

我是iOS的新手,并且想使用Decodable解析JSON,但无法解决该问题,我应该如何解决呢?

The view controller where I am trying to parse the data

class ViewController: UIViewController {

    var servers = [Server]()

    let apiUrl = "https://someurl/api/dashboard"

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let url = URL(string: self.apiUrl) else { return }

        getDataFrom(url)
    }

    fileprivate func getDataFrom(_ url: URL) {
        URLSession.shared.dataTask(with: url){ (data, response, error) in

            guard let data = data else { return }

            do {
                let apiResponse = try JSONDecoder().decode(Server.self, from: data)
                print(apiResponse)
            } catch let jsonError {
                print(jsonError)
            }
            }.resume()
    }


}

我要确认可解码协议的Server.swift文件

struct Server: Decodable {
    let current_page: Int
    let data: [ServerData]
    let first_page_url: String
}

struct ServerData: Decodable {
    let hostname: String
    let ipaddress: String
    let customer: [Customer]
    let latest_value: [LatestValue]
}



struct Customer: Decodable {
    let name: String
    let contact_person :String
    let email: String
}


struct LatestValue: Decodable {
    let systemuptime: String
    let memtotal: Float
    let memfree: Double
    let loadaverage: Float
}

No value associated with key CodingKeys我收到此错误

服务器的响应

{
  "servers": {
    "current_page": 1,
    "data": [
      {
        "hostname": "johndoes",
        "ipaddress": "10.0.2.99",
        "id": 7,
        "latest_value_id": 1130238,
        "customers": [
          {
            "name": "Jane Doe",
            "contact_person": "John Doe",
            "id": 2,
            "email": "john.@example.com",
            "pivot": {
              "server_id": 7,
              "customer_id": 2
            }
          }
        ],
        "latest_value": {
          "id": 1130238,
          "server_id": 7,
          "systemuptime": "80days:10hours:23minutes",
          "memtotal": 3.7,
          "memfree": 1.6400000000000001,
          "loadaverage": 2.25,
          "disktotal": {
            "dev-mapper-centos-root_disktotal": "38",
            "dev-mapper-proquote-xfs-lvm_disktotal": "200"
          },
          "diskused": "{\"dev-mapper-centos-root_diskused\":\"16\",\"dev-mapper-proquote-xfs-lvm_diskused\":\"188\"}",
          "custom_field": "[]",
          "additional_attributes": {
            "fathom": {
              "name": "fathom",
              "status": 1
            },
            "trenddb": {
              "name": "trenddb",
              "status": 1
            },
            "trendwi": {
              "name": "trendwi",
              "status": 1
            },
            "appsrv": {
              "name": "appsrv",
              "status": 1
            }
          },
          "created_at": "2019-06-15 02:25:02",
          "updated_at": "2019-06-15 02:25:02"
        }
      }
    ]
  },
  "message": "Success"
}

1 个答案:

答案 0 :(得分:1)

您的数据结构中似乎没有几个不同的错误。

  • 首先,当您的json在字典Server中包含服务器时,您尝试解码{"servers": ... },因此请为其使用父根对象。
  • 您在latest_value中的ServerData被定义为数组,而应该是LatestValue结构而不是[LatestValue]
  • 您的json中没有first_page_url元素,但是您的Server结构具有该属性,使其成为可选属性,以便JSONDecoder仅在存在时对其进行解码。

这是您的精炼数据模型。

struct Response: Decodable {
    let servers: Server
}

struct Server: Decodable {
    let current_page: Int
    let data: [ServerData]
    let first_page_url: String?
}

struct ServerData: Decodable {
    let hostname: String
    let ipaddress: String
    let customers: [Customer]
    let latest_value: LatestValue
}



struct Customer: Decodable {
    let name: String
    let contact_person :String
    let email: String
}


struct LatestValue: Decodable {
    let systemuptime: String
    let memtotal: Float
    let memfree: Double
    let loadaverage: Float
}

然后像这样解码而不是解码Response的{​​{1}}

Server