Simple and clean way to convert JSON string to Object in Swift

前端 未结 16 1208
挽巷
挽巷 2020-11-28 23:27

I have been searching for days to convert a fairly simple JSON string to an object type in Swift but with no avail.

Here is the code for web service call:



        
16条回答
  •  一向
    一向 (楼主)
    2020-11-29 00:18

    It might be help someone. Similar example.

    This is our Codable class to bind data. You can easily create this class using SwiftyJsonAccelerator

     class ModelPushNotificationFilesFile: Codable {
    
      enum CodingKeys: String, CodingKey {
        case url
        case id
        case fileExtension = "file_extension"
        case name
      }
    
      var url: String?
      var id: Int?
      var fileExtension: String?
      var name: String?
    
      init (url: String?, id: Int?, fileExtension: String?, name: String?) {
        self.url = url
        self.id = id
        self.fileExtension = fileExtension
        self.name = name
      }
    
      required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        url = try container.decodeIfPresent(String.self, forKey: .url)
        id = try container.decodeIfPresent(Int.self, forKey: .id)
        fileExtension = try container.decodeIfPresent(String.self, forKey: .fileExtension)
        name = try container.decodeIfPresent(String.self, forKey: .name)
      }
    
    }
    

    This is Json String

        let jsonString = "[{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/tulips.png\"},
    
    {\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/arctichare.png\"},
    
    {\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/serrano.png\"},
    
    {\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/peppers.png\"},
    
    {\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/pool.png\"}]"
    

    Here we convert to swift object.

       let jsonData = Data(jsonString.utf8)
    
            let decoder = JSONDecoder()
    
            do {
                let fileArray = try decoder.decode([ModelPushNotificationFilesFile].self, from: jsonData)
                print(fileArray)
                print(fileArray[0].url)
            } catch {
                print(error.localizedDescription)
            }
    

提交回复
热议问题