Как проанализировать этот тип формата JSON в Swift 4 с декодируемым? - PullRequest
0 голосов
/ 24 октября 2018
{
  "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}]"
  }
}

Ответы [ 2 ]

0 голосов
/ 26 октября 2018

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)
}
0 голосов
/ 24 октября 2018

Во-первых, вам, возможно, придется создавать модели, что подтверждает Codable Protocol.Вы можете использовать любые онлайн-инструменты для форматирования 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()
...