How to convert NSObject class object into JSON in Swift?

前端 未结 3 1482
心在旅途
心在旅途 2021-01-19 15:54

I have

var  contacts : [ContactsModel] = []

and

class ContactsModel: NSObject
{
   var contactEmail : String?
   var cont         


        
3条回答
  •  醉话见心
    2021-01-19 16:42

    Your custom object can't be converted to JSON directly. NSJSONSerialization Class Reference says:

    An object that may be converted to JSON must have the following properties:

    • The top level object is an NSArray or NSDictionary.

    • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.

    • All dictionary keys are instances of NSString.

    • Numbers are not NaN or infinity.

    You might convert your object to a Dictionary manually or use some libraries like SwiftyJSON, JSONModel or Mantle.

    Edit: Currently, with swift 4.0+, you can use Codable protocol to easily convert your objects to JSON. It's a native solution, no third party library needed. See Using JSON with Custom Types document from Apple.

提交回复
热议问题