如何使用可解码的Swift 4解析这种类型的json格式?

时间:2018-10-24 06:16:51

标签: ios json parsing swift4 decodable

ResourceTranscoder<InputStream, ImageData>

2 个答案:

答案 0 :(得分:0)

首先,您可能必须创建模型,以确认可编码协议。您可以使用任何在线工具来格式化JSON和创建模型。在给定的代码响应中,Model将获得解析的数据。

   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()

答案 1 :(得分: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)
}