Serialize an Array of CBLModel objects into JSON

70 views
Skip to first unread message

Nate Smith

unread,
Jun 3, 2014, 11:06:50 PM6/3/14
to mobile-c...@googlegroups.com
I have an array containing CBLModel that I'd like to serialize into JSON.  Each model object adhears to the <CBLJSONEncoding> delegate.  I'm trying to do it like this:

-(void)saveToJSON:(NSMutableArray*)arr {
   
NSError *error;
   
self.json = [CBLJSON
                 dataWithJSONObject
:arr
                 options
:CBLJSONWritingPrettyPrinted
                   error
:&error];
   
if (! self.json) {
       
NSLog(@"Got an error in Categories -> convertToJSON: %@", error);
   
}
}

but that fails on with the error "Invalid type in JSON write (SBCategory)", SBCategory being my CBLModel object. 

Jens Alfke

unread,
Jun 3, 2014, 11:13:57 PM6/3/14
to mobile-c...@googlegroups.com
+[CBLJSON dataWithJSONObject:] is just a wrapper around NSJSONSerialization, which only knows how to serialize the standard types (NSString, NSArray, etc.)

If you want to get a JSON-serializable form of a CBLModel, call -propertiesToSave on it. Then you can collect those into an NSArray and turn that into JSON.

—Jens

Nate Smith

unread,
Jun 4, 2014, 10:43:25 AM6/4/14
to mobile-c...@googlegroups.com
So what's the point of - (id)initWithJSON:(id)jsonObject and - (id)encodeAsJSON then?  In my mind conforming to the CBLJSONEncoding and implementing these methods would allow my object to be automatically serialized somehow, I just don't know how :-) 

Jens Alfke

unread,
Jun 6, 2014, 6:25:47 PM6/6/14
to mobile-c...@googlegroups.com

On Jun 4, 2014, at 7:43 AM, Nate Smith <nates...@gmail.com> wrote:

So what's the point of - (id)initWithJSON:(id)jsonObject and - (id)encodeAsJSON then?  In my mind conforming to the CBLJSONEncoding and implementing these methods would allow my object to be automatically serialized somehow, I just don't know how :-)  

CBLModel uses those. If you declare an @property in a CBLModel whose type is a class that implements CBLJSONEncoding, or whose type is an array and you specify that the item type is a class that implements CBLJSONEncoding, then CBLModel will encode/decode the objects for you.

It would indeed be nice if CBLJSON could transparently encode these too. But to do that I’d have to use a custom JSON encoder instead of NSJSONSerialization, and I’ve been leery of doing that.

—Jens
Reply all
Reply to author
Forward
0 new messages