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

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

    for swift 3/4

    extension String {
        func toJSON() -> Any? {
            guard let data = self.data(using: .utf8, allowLossyConversion: false) else { return nil }
            return try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
        }
    }
    

    Example Usage:

     let dict = myString.toJSON() as? [String:AnyObject] // can be any type here
    

提交回复
热议问题