如何使用空根名称读取 JSON 结果 来自 API - XCODE11 (Swift)



示例 JSON 数据

[ { "Active": "39", "BillingProperty": null, "DAS": "test_user|aman|LINEMANUSER", "Entity": "dendb", "GULCOCode": "M000100010000100001000000420", "Inactive": "572", "LCOCode": "TEST-HO", "LcoCategory": "Prepaid", "Status": "M000100010000100001000004848", "Success": "1", "Total": "0", "alcrights": "1", "freshActivation": "1", "profileexist": "1", "promorights": "1", "staffID": null, "userID": "M000100010000100001000004848", "walletBalance": 0.35 } ]
======================================
到目前为止我尝试过!! ====
=================================
struct MyClass :Codable 
{ 
var Status: String 
}
let session = URLSession.shared session.dataTask(with: request) { (data, response, error) in 
do { let countries=try JSONDecoder().decode(MyClass.self, from : data!) 
print(countries.Status)  
} 
catch { 
print ("error"); 
} 
}.resume()

试试这个:(我建议使用这个网站:https://app.quicktype.io/(

// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
// let welcome = try? newJSONDecoder().decode(Welcome.self, from: jsonData)

import Foundation
// MARK: - WelcomeElement
struct WelcomeElement: Codable {
let active: String
let billingProperty: JSONNull?
let das, entity, gulcoCode, inactive: String
let lcoCode, lcoCategory, status, success: String
let total, alcrights, freshActivation, profileexist: String
let promorights: String
let staffID: JSONNull?
let userID: String
let walletBalance: Double
enum CodingKeys: String, CodingKey {
case active = "Active"
case billingProperty = "BillingProperty"
case das = "DAS"
case entity = "Entity"
case gulcoCode = "GULCOCode"
case inactive = "Inactive"
case lcoCode = "LCOCode"
case lcoCategory = "LcoCategory"
case status = "Status"
case success = "Success"
case total = "Total"
case alcrights, freshActivation, profileexist, promorights, staffID, userID, walletBalance
}
}
typealias Welcome = [WelcomeElement]
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
public var hashValue: Int {
return 0
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}

最新更新