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

前端 未结 16 1243
挽巷
挽巷 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:09

    For iOS 10 & Swift 3, using Alamofire & Gloss:

    Alamofire.request("http://localhost:8080/category/en").responseJSON { response in
    
    if let data = response.data {
    
        if let categories = [Category].from(data: response.data) {
    
            self.categories = categories
    
            self.categoryCollectionView.reloadData()
        } else {
    
            print("Casting error")
        }
      } else {
    
        print("Data is null")
      }
    }
    

    and here is the Category class

    import Gloss
    
    struct Category: Decodable {
    
        let categoryId: Int?
        let name: String?
        let image: String?
    
        init?(json: JSON) {
            self.categoryId = "categoryId" <~~ json
            self.name = "name" <~~ json
            self.image = "image" <~~ json
        }
    }
    

    IMO, this is by far the most elegant solution.

提交回复
热议问题