How to serialize or convert Swift objects to JSON?

后端 未结 9 1733
灰色年华
灰色年华 2020-11-28 03:33

This below class

class User: NSManagedObject {
  @NSManaged var id: Int
  @NSManaged var name: String
}

Needs to be converted to

9条回答
  •  迷失自我
    2020-11-28 03:55

    I worked a bit on a smaller solution that doesn't require inheritance. But it hasn't been tested much. It's pretty ugly atm.

    https://github.com/peheje/JsonSerializerSwift

    You can pass it into a playground to test it. E.g. following class structure:

    //Test nonsense data
    class Nutrient {
        var name = "VitaminD"
        var amountUg = 4.2
    
        var intArray = [1, 5, 9]
        var stringArray = ["nutrients", "are", "important"]
    }
    
    class Fruit {
        var name: String = "Apple"
        var color: String? = nil
        var weight: Double = 2.1
        var diameter: Float = 4.3
        var radius: Double? = nil
        var isDelicious: Bool = true
        var isRound: Bool? = nil
        var nullString: String? = nil
        var date = NSDate()
    
        var optionalIntArray: Array = [1, 5, 3, 4, nil, 6]
        var doubleArray: Array = [nil, 2.2, 3.3, 4.4]
        var stringArray: Array = ["one", "two", "three", "four"]
        var optionalArray: Array = [2, 4, 1]
    
        var nutrient = Nutrient()
    }
    
    var fruit = Fruit()
    var json = JSONSerializer.toJson(fruit)
    
    print(json)
    

    prints

    {"name": "Apple", "color": null, "weight": 2.1, "diameter": 4.3, "radius": null, "isDelicious": true, "isRound": null, "nullString": null, "date": "2015-06-19 22:39:20 +0000", "optionalIntArray": [1, 5, 3, 4, null, 6], "doubleArray": [null, 2.2, 3.3, 4.4], "stringArray": ["one", "two", "three", "four"], "optionalArray": [2, 4, 1], "nutrient": {"name": "VitaminD", "amountUg": 4.2, "intArray": [1, 5, 9], "stringArray": ["nutrients", "are", "important"]}}
    

提交回复
热议问题