Convert NSObject to JSON string

2019-08-12 23:28发布

问题:

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.