Parse a Json in Swift

后端 未结 1 1579
半阙折子戏
半阙折子戏 2020-12-22 04:18

I have a problem to parse a Json file. try to parse a Json file:

{
  \"id\": 1234,
  \"lists\": {
    \"pause\": {
      \"attached\": [
        {
                   


        
相关标签:
1条回答
  • 2020-12-22 04:34

    Create this as model class for you json:

    import Foundation
    
    class MyItem: Codable {
        let id: Int
        let lists: Lists
        let time: Time
    }
    
    class Lists: Codable {
        let pause: Pause
    }
    
    class Pause: Codable {
        let attached: [Attached]
    }
    
    class Attached: Codable {
        let from, to, length: Int
    }
    
    class Time: Codable {
        let start_time, end_time: Int
    }
    
    // MARK: - Helper functions for creating encoders and decoders
    fileprivate func newJSONDecoder() -> JSONDecoder {
        let decoder = JSONDecoder()
        if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
            decoder.dateDecodingStrategy = .iso8601
        }
        return decoder
    }
    
    fileprivate func newJSONEncoder() -> JSONEncoder {
        let encoder = JSONEncoder()
        if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
            encoder.dateEncodingStrategy = .iso8601
        }
        return encoder
    }
    

    Then you can parse it like this:

    let myItem = try? newJSONDecoder().decode(MyItem.self, from: jsonData)
    // Read from (for example)
    let from = myItem.lists.pause.attached[0].from
    
    0 讨论(0)
提交回复
热议问题