gpt4 book ai didi

json - 如何在 Swift 中解析多级 json 结构?

转载 作者:行者123 更新时间:2023-12-03 14:48:25 26 4
gpt4 key购买 nike

来自服务器的 JSON 如下所示:

一个字典,其中的值是另一个字典。

{
"S1": {
"vpn_status": 2,
"vpn_name": "vpn1"
},
"S2": {
"vpn_status": 1,
"vpn_name": "vpn2"
}
}

我创建了以下结构来解析它。

public struct ServerStatusResult {

public let vpnName: String
public let status: Int

init?(json: [String: Any]) {
guard
let vpnName = json["vpn_name"] as? String,
let status = json["vpn_status"] as? Int
else {
return nil
}
self.vpnName = vpnName
self.status = status
}
}

调用服务器的函数是:

typealias serverStatusCompletedClosure = (_ status: Bool, _ result: Dictionary<String,ServerStatusResult>?, _ error: ServiceError?)->Void

func serverStatus(email: String, password: String, complete: @escaping serverStatusCompletedClosure) {
let url = URL(string: "...")!
try? self.httpClient.get(url: url,
token: "...",
email: email,
password: password)
{ (data, response, error) in
if let error = error {
complete(false, nil, ServiceError.invalidSession)
} else if let httpResponse = response as? HTTPURLResponse {
switch (httpResponse.statusCode) {
case 200:
var result: [String:ServerStatusResult]? = nil
result = try! JSONSerialization.jsonObject(with: data!, options: []) as! Dictionary<String, ServerStatusResult>
complete(true, result, nil)

这是我的 json 转换失败的地方。

Could not cast value of type '__NSDictionaryI' (0x7fff8eaee9b0) to 'app.ServerStatusResult' (0x10021dec0).

请问我错过了什么?

最佳答案

你可以用Decodable和字典来解决

首先让你的结构符合Decodable

public struct ServerStatusResult: Decodable {
public let vpnName: String
public let status: Int

enum CodingKeys: String, CodingKey {
case vpnName = "vpn_name"
case status = "vpn_status"
}
}

然后解码就很简单了

do {
let result = try JSONDecoder().decode([String: ServerStatusResult].self, from: data)
print(result) //or in you case complete(true, result, nil)
} catch {
print(error)
}

关于json - 如何在 Swift 中解析多级 json 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61007676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com