簡體   English   中英

如何在 swift 4 中使用可解碼解析這種類型的 json 格式?

[英]How to parse this type of json format in swift 4 with decodable?

{
  "type": "Success",
  "message": "",
  "fitting": {
    "fitterID": "96ba096c-f0aa-11e7-a67a-76478bc72e4d",
    "fitID": "09d399c0-7d74-4578-a138-5f4b02ba2e80",
    "leftNotesJSON": "[{\"class\":\"FitNote\",\"text\":\"Saddle Down\",\"leftfoot\":false},{\"class\":\"FitNote\",\"text\":\"Saddle Down\",\"leftfoot\":false},{\"class\":\"FootBottomNote\",\"leftfoot\":false}]",
    "rightNotesJSON": "[{\"s3Bucket\":\"8190ba10-d310-11e3-9c1a-0800200c9a66\",\"angle\":0,\"leftfoot\":false,\"shoulderAngle\":0,\"hipAngle\":0,\"s3Key\":\"FD0F5AE6-8193-4980-AD11-C42FEF064B8B\",\"class\":\"AngleNote\",\"kneeAngle\":0}]"
  }
}

您問題中的 json 無效。 我將在回答中使用以下 json:

let json = """
{
  "type": "Success",
  "message": "",
  "fitting": {
    "fitterID": "96ba096c-f0aa-11e7-a67a-76478bc72e4d",
    "fitID": "09d399c0-7d74-4578-a138-5f4b02ba2e80",
    "leftNotesJSON": [{"class":"FitNote","text":"Saddle Down","leftfoot":false},{"class":"FitNote","text":"Saddle Down","leftfoot":false},{"class":"FootBottomNote","leftfoot":false}],
    "rightNotesJSON": [{"s3Bucket":"8190ba10-d310-11e3-9c1a-0800200c9a66","angle":0,"leftfoot":false,"shoulderAngle":0,"hipAngle":0,"s3Key":"FD0F5AE6-8193-4980-AD11-C42FEF064B8B","class":"AngleNote","kneeAngle":0}]
  }
}
"""

讓我們定義可解碼的結構:

struct Response: Codable {
    let type, message: String
    let fitting: Fitting
}

struct Fitting: Codable {
    let fitterID, fitID: String
    let leftNotesJSON: [LeftNotesJSON]
    let rightNotesJSON: [RightNotesJSON]
}

struct LeftNotesJSON: Codable {
    let leftNotesJSONClass: String
    let text: String?
    let leftfoot: Bool

    //Define the coding keys since the json contains "class" as a key
    enum CodingKeys: String, CodingKey {
        case leftNotesJSONClass = "class"
        case text, leftfoot
    }
}

struct RightNotesJSON: Codable {
    let s3Bucket: String
    let angle: Int
    let leftfoot: Bool
    let shoulderAngle, hipAngle: Int
    let s3Key, rightNotesJSONClass: String
    let kneeAngle: Int

    //Define the coding keys since the json contains "class" as a key  
    enum CodingKeys: String, CodingKey {
        case s3Bucket, angle, leftfoot, shoulderAngle, hipAngle, s3Key
        case rightNotesJSONClass = "class"
        case kneeAngle
    }
}

讓我們從json中取出數據:

guard let data = json.data(using: .utf8) else {
    fatalError("Couldn't get data from json")
}

然后解碼

do {
    let response = try JSONDecoder().decode(Response.self, from: data)

    //Here and now you can use the properties of the response
    print(response.type)
    print(response.message)
    print(response.fitting.fitID)
    print(response.fitting.fitterID)
    print(response.fitting.leftNotesJSON.map {$0.leftfoot})
    print(response.fitting.rightNotesJSON.map{$0.kneeAngle})
} catch {
    print(error)
}

首先,您可能必須創建模型,以確認 Codable 協議。 您可以使用任何在線工具來格式化 JSON 和創建模型。 在給定的代碼響應模型中將獲得解析的數據。

   import Foundation
    struct Base : Codable {
        let type : String?
        let message : String?
        let fitting : Fitting?
        enum CodingKeys: String, CodingKey {
            case type = "type"
            case message = "message"
            case fitting = "fitting"
        }
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            type = try values.decodeIfPresent(String.self, forKey: .type)
            message = try values.decodeIfPresent(String.self, forKey: .message)
            fitting = try values.decodeIfPresent(Fitting.self, forKey: .fitting)
        }
    }


    import Foundation
    struct Fitting : Codable {
        let fitterID : String?
        let fitID : String?
        let leftNotesJSON : String?
        let rightNotesJSON : String?

        enum CodingKeys: String, CodingKey {

            case fitterID = "fitterID"
            case fitID = "fitID"
            case leftNotesJSON = "leftNotesJSON"
            case rightNotesJSON = "rightNotesJSON"
        }

        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            fitterID = try values.decodeIfPresent(String.self, forKey: .fitterID)
            fitID = try values.decodeIfPresent(String.self, forKey: .fitID)
            leftNotesJSON = try values.decodeIfPresent(String.self, forKey: .leftNotesJSON)
            rightNotesJSON = try values.decodeIfPresent(String.self, forKey: .rightNotesJSON)
        }

    }

    let task = URLSession.shared.dataTask(with: <YOUR URL>) { (data, response, error) in
        if let data = data {
            let jsonDecoder = JSONDecoder()
            let responseModel = try jsonDecoder.decode(Base.self, from: data)
        }
    }
    task.resume()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM