How to convert NSObject class object into JSON in Swift?

前端 未结 3 1486
心在旅途
心在旅途 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.

提交回复
热议问题