2

Sample Code:

NSString *jsonObject = ...;
BOOL isValidJSONObject = [NSJSONSerialization isValidJSONObject:jsonObject];
id jsonResponse = [NSJSONSerialization JSONObjectWithData:parsedData
                                                                options:NSJSONReadingAllowFragments
                                                                  error:&jsonError];

Issue:

If jsonObject contains string data with newline characters, then NSJSONSerialization fails to parse and return a valid jsonRespone object. It returns following error:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unescaped control character around character 119.) UserInfo=0x10ba9fef0 {NSDebugDescription=Unescaped control character around character 119.}

Sample JSON String (with newline character):

{"Name" : "Lorum","Description" : "Sample: 
Lorum ipsum","Quantity" : 1,"Type" : 1}

What's the best way to handle this situation? Newline/ line break character should be valid in this case.

Mustafa
  • 20,504
  • 42
  • 146
  • 209
  • That's not valid JSON. Newlines should be escaped. – duci9y Aug 09 '14 at 07:28
  • Hope help. http://stackoverflow.com/questions/11591784/parsing-json-containing-new-line-characters – KudoCC Aug 09 '14 at 07:43
  • @duci9y When you say "escape" what do you mean exactly? – Mustafa Aug 09 '14 at 11:08
  • For now, I just changed newline with
    tag, and then replaced
    with newline (at application end). Alternately, I could have encoded the data. I don't like this approach. I think NSJSONSerialization should handle the newline characters (\n and \r). JSONKit handles this with the option JKParseOptionUnicodeNewlines, and I like that!
    – Mustafa Aug 09 '14 at 12:55
  • JSONKit provides that option for you as a favor. Your JSON would still be incorrect according to the standard. – duci9y Aug 09 '14 at 13:06

1 Answers1

0

YES, double backslash is needed. However slash is not need to write twice. For example,

jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:@[@"line 0\nline1", @"http://twitter.com"] options:0 error:nil] encoding:NSUTF8StringEncoding];

when hover your cursor on jsonString, Xcode will tell you what it exactly want. If you write

jsonString = @"[\"http://twitter.com\"]",

you can get correct answer when using NSJSONSerialization to parse the string. Even you know the more suitable input is

jsonString = @"[\"http:\\/\\/twitter.com\"]".

DawnSong
  • 4,752
  • 2
  • 38
  • 38