Convert NSObject to JSON string

Deadly 提交于 2019-12-13 02:45:32

问题


I have a class that conforms to NSObject and has fields like NSNumber and NSMutableArray, so cannot really use Codable here.

So the class is like this:

class Custom: NSObject {
    var users: NSMutableArray?
    var type: NSNumber?
    .. and many more fields
}

Now i have an object of this class and want to get JSON string from that object :

I have tried following :

let json = try? JSONSerialization.data(withJSONObject: customObject, options: JSONSerialization.WritingOptions.prettyPrinted) as? [String: Any]

let json = try? JSONSerialization.data(withJSONObject: paymentData, options: JSONSerialization.WritingOptions.prettyPrinted)

The above two code gave crash like Invalid top-level type in JSON write'

And used SwiftyJson library too but that too gave the error SwiftyJSON.SwiftyJSONError.unsupportedType

I wanted to try Codable but that requires me to convert NSNumber to Int and MSMutableArray to Array but I cannot really change this as I have used this code in many other places and also my code is working with Objective C so either I had to use NSNumber or had to convert between Int and NSNumber too many times.

Is there a solution that doesn't require changing the current implementation of class and still convert the object to json. Any help would be appreciated.

来源:https://stackoverflow.com/questions/52369799/convert-nsobject-to-json-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!