Error Domain=CBLHTTP Code=400 "400 Invalid JSON"

I am a newbie to Couchbase and have a question on saving data to the Couchbase.

The “putProperties” failed with the error: Error Domain=CBLHTTP Code=400 “400 Invalid JSON” when I do this:

NSString *eventDate = “2015-02-24 10:03:34 +0000”;
NSDictionary *eventInfo = @{@“EventDate” : eventDate};

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
CBLDocument *doc = [appDelegate.database createDocument];

NSError *error;
if ([doc putProperties: eventInfo error: &error])  {
    
    NSLog(@"success");
    
} else {
    NSLog(@"fail");
    
}

However, if I just add the direct value to the eventInfo like this:

NSDictionary *eventInfo = @{@“EventDate” : @“2015-02-24 10:03:34 +0000”}; // putProperties works without any error.

I don’t get it. Can you please help?

Thank you.

That error means the eventInfo object contains objects that can’t be converted to JSON.

Your code looks as though it should work. But you haven’t pasted in the exact source code (there’s an @ missing on the first line) so you may have omitted some significant clue. Could you paste in the exact source code that fails?

Also, if you set a breakpoint at the -putProperties: call you can examine the value of eventInfo and double-check that it’s what you expect.

Thanks Jens.

You are right about the object eventInfo object contains objects that can’t be converted to JSON.

The exact code was NSDictionary *eventInfo = @{@“EventDate” : _pickerViewDate.date}; where _pickerViewDate.date is the date picker with value of “2015-02-24 10:03:34 +0000”.

Although the value looks like a string, it’s actually a date. I fixed it by converting the value to string first with

NSDictionary *eventInfo = @{@“EventDate” : [NSString stringWithFormat:@"%@", _pickerViewDate.date]};

Ah, that explains it. You should use a standardized format for storing dates, though, if you care about interoperability. (Also, I believe the default string representation of an NSDate may reflect the current locale, meaning that it will differ depending on what country the user is in or what system calendar prefs they set.)

We have a method [CBLJSON jsonObjectWithDate:] that converts an NSDate to an NSString in ISO-8601 format, which is the de facto standard for storing dates in JSON.

1 Like

This is great! Let me look at CBLJSON.h to familiarize myself.

On a side note, if I allow “[database createDocument]” to generate the UUID as document ID, how can I retrieve the document ID to use for editing the document later? Is there a special field which I can retrieve the document ID?

Thanks.

You mean like the CBLDocument.documentID property?

I think what you want is the _id property (as documented under special properties on this page.

Thanks Jen and borrrden… That was it!

It’s always a good idea to look at the API docs. The ones for iOS are here.