How to convert NSObject class object into JSON in Swift?

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

I have

var  contacts : [ContactsModel] = []

and

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


        
相关标签:
3条回答
  • 2021-01-19 16:29

    If you just want a simple Swift object to JSON static function without any inheritance or dependencies to NSObject or NS-types directly. Check out:

    https://github.com/peheje/JsonSerializerSwift

    Full disclaimer. I made it. Simple use:

    //Arrange your model classes
    class Object {
      var id: Int = 182371823
      }
    class Animal: Object {
      var weight: Double = 2.5
      var age: Int = 2
      var name: String? = "An animal"
      }
    class Cat: Animal {
      var fur: Bool = true
    }
    
    let m = Cat()
    
    //Act
    let json = JSONSerializer.toJson(m)
    

    Currently supports standard types, optional standard types, arrays, arrays of nullables standard types, array of custom classes, inheritance, composition of custom objects.

    0 讨论(0)
  • 2021-01-19 16:37

    You can use NSJSONSerialization for array when array contains only JSON encodable values (string, number, dictionary, array, nil)

    first you need to create the JSON object then you can use it (your code is crashing because contact is not a JSON object!)

    you can refere below link

    https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/#//apple_ref/doc/uid/TP40010946-CH1-SW9

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题