Creating an object that works with NSJSONSerializa

2019-06-26 20:36发布

问题:

At the moment in order to use this function I'm "converting" my object into a dictionary. i.e. the property names become the keys and the property values become the values.

Is there a way to properly do this so that an object will work with this function?

i.e. similar to encodeWithCoder and initWithCoder for use with NSUserDefaults.

I'd like to do ...

NSData *data = [NSJSONSerialization dataWithJSONObject:myObject options:0 error:nil];

at the moment I do something like...

NSData *data = [NSJSONSerialization dataWithJSONObject:[myObject dictionaryRepresentation] options:0 error:nil];

回答1:

Take a look at JSONCoding, which builds on NSJSONSerialization with an NSCoding interface.