iOS - NSJSONSerialization: Unable to convert data to string around character - ios

I'm getting this error while parsing JSON:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unable to convert data to string around character 73053.) UserInfo=0x1d5d8250 {NSDebugDescription=Unable to convert data to string around character 73053.}
Any suggestions how to fix this?
ADDED
As it says in error report, the parser can't go through the character at position 73053, which is "ø" in my JSON response. As far as I know characters like Ø,Å,Æ etc. shouldn't be a problem for json parsers?

Yes, I have the same problem with encoding issue and got the above error. I got the NSData from server as encoding:NSISOLatin1StringEncoding. So I had to convert it to UTF8 before parsing it using NSJSONSerialization.
NSError *e = nil;
NSString *iso = [[NSString alloc] initWithData:d1 encoding:NSISOLatin1StringEncoding];
NSData *dutf8 = [iso dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:dutf8 options:NSJSONReadingMutableContainers error:&e];

Switf 3
let responseStrInISOLatin = String(data: data, encoding: String.Encoding.isoLatin1)
guard let modifiedDataInUTF8Format = responseStrInISOLatin?.data(using: String.Encoding.utf8) else {
print("could not convert data to UTF-8 format")
return
}
do {
let responseJSONDict = try JSONSerialization.jsonObject(with: modifiedDataInUTF8Format)
} catch {
print(error)
}

Check that the data you're parsing is actually valid JSON (and not just 'nearly' JSON). That error is known to occur when you have a different data format that can't be parsed as JSON. See for example:
iOS 5 JSON Parsing Results in Cocoa Error 3840
Do you have a top-level container in your JSON too? An array or dictionary. Example:
{ "response" : "Success" }
Update
JSON's default encoding is UTF-8. Special/exotic characters aren't a problem for UTF-8, but please ensure that your server is returning its content properly encoded as UTF-8. Also, have you done anything to tell your JSON interpretter to use a different encoding?
If your JSON is coming from a web service, put the URL into this page to see what it has to see about the encoding:
http://validator.w3.org/

Swift 5:
Yes, i got the same error while parsing JSON data.
Solution : You have to first convert response data into String and then convert that Sting to Data using UTF8 encoding before decoding.
let utf8Data = String(decoding: responseData, as: UTF8.self).data(using: .utf8)

Related

Error Domain=NSCocoaErrorDomain Code=3840 "Invalid escape sequence around character 746."

I am getting this error
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid escape sequence around character 746." UserInfo={NSDebugDescription=Invalid escape sequence around character 746.}
Here is my code to parse JSON:
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
strResponse=[self stringByRemovingControlCharacters:strResponse];
NSData *jsonData = [strResponse dataUsingEncoding:NSUTF8StringEncoding];
responseObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&serializationError
Using this code I am getting response object in other API.
but in my API contains HTML tags.
My issue is I am getting JSON string but it is not parsing in JSON.
for this API I am getting error
"Error Domain=NSCocoaErrorDomain Code=3840".
My conclusion is that JSON is not parsing properly in above code.
The string from Ur backend may be invalid JSON,it may contain "\s""\n""\t" or other tab character。And in Xcode u print it will not see the tab character,the console will not print them.You may get the JSON and find if there are tab characters.

NSURLConnection : JSON text did not start with array or object and option to allow fragments not set

I get the following error from NSURLConnection connectionDidFinishLoading
"The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text
did not start with array or object and option to allow fragments not
set.) UserInfo=0x7b71dbb0 {NSDebugDescription=JSON text did not start
with array or object and option to allow fragments not set.}
I used the following code :
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
id json = [NSJSONSerialization JSONObjectWithData:_urlData options:kNilOptions error:&error];
if (error) {
NSLog(#"Loading Error = %#",error);
}
}
The following is my json response :
{
"result":"success",
"details":[
{
"id":"11531",
"user_name":"",
"fullname":"aa",
"email_address":"aa",
"user_type":"a",
"server":"",
"server_email":"",
"server_password":"",
"password":"0cc175b9c0f1b6a831c399e269772661",
"clean_password":"a",
"gender":"",
"ceo_name":"",
"ceo_picture":"",
"ceo_contact":"",
"ceo_contact_pic":"",
"company_name":"a",
"freight_company_name":"",
"freight_company_email":"",
"company_url":"11531",
"company_keyword":"",
"company_description":"",
"address":"",
"province":"",
"postal_code":"",
"phone_number":"",
"fax_number":"",
"website":"",
"city":"",
"b_category":"",
"main_products":"",
"cellphone":"a",
"country":"0",
"states":"",
"company_status":"1",
"joindate":"0",
"varificationcode":"",
"activation_status":"1",
"new_email":"",
"email_activation_status":"",
"facebook_url":"",
"twitter_url":"",
"company_update_status":"0",
"last_access_date":"0000-00-00",
"ip_address":"",
"ip_block":"0",
"user_id":null,
"company_id":null,
"video_url":"",
"oauth_uid":"",
"oauth_provider":"",
"get_color":"",
"comp_name_size":"13",
"member_type":"",
"mark_status":"1",
"ip_address_intension":"",
"fbId":"",
"twitterId":"",
"profile_picture":"",
"device_token":""
}
]
}
I have tried all the solutions in stackOverflow but in vein.
Set option value to NSJSONReadingAllowFragments instead of kNilOptions
I have tested your JSON taking it in a local file
id json = [NSJSONSerialization JSONObjectWithData:contentOfLocalFile
options:NSJSONReadingAllowFragments
error:&deserializingError];
NSLog the actual data that you are getting, not the string, and check the first bytes. JSONSerializer didn't find a { or a [ as the first character, so you probably have some zero bytes, or byte order marks, or some other invisible characters like that.
In addtion to Janmenjaya's answer i would like to add:-
I have faced this issue twice in different API's. The problem each time that i had was
First time the response that i was receiving was not in correct format. Remember the format must always start with a "[" or "{". So that was corrected from backend.
Secondly , i was trying to hit an URL which had a word "video" in it for ex http://www.xyz/video123.com and websites related to name video have been blocked in our office. Therefore ensure that the network that you are using has no such restrictions.
Postman will show you correct response but in devices or simulators you will face issues.
Please ensure these cases also.

NSJSONSerialization JSONObjectWithData where data contains line break characters

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.
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\"]".

Need some help to convert JSON string to NSDictionary

How do I convert this NSString to NSDictionary? Below is the NSString:
NSLog(#"urlstring: %#", urlString);
outputs: urlstring: "{"url":"http://mydomain.com/metaioman_target.png"}"
Then I convert it to JSON and then to NSDictionary:
NSData *json = [urlString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:json options:0 error:&e];
However, when I NSLog the dic it is null, and printing the error gives the following:
error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)"
(JSON text did not start with array or object and option to allow fragments not set.)
UserInfo=0x16641de0 {NSDebugDescription=JSON text did not start with
array or object and option to allow fragments not set.}
However, overwriting the urlString with:
#"{\"ID\":\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":\"Content\":65,\"type\":\"text\"}}"
converts it successfully.
I guess something is wrong with the quotes?
If your string was valid (in terms of JSON) NSLog should output:
urlstring: {"url":"http://mydomain.com/metaioman_target.png"}
so your problem is the outer double quotes, get rid of them and it will deserialize just fine.
You have double quotes around the actual JSON string.
You need to check when these quotes are added and get rid of them.
urlString should be {"url":"http://mydomain.com/metaioman_target.png"} instead of "{"url":"http://mydomain.com/metaioman_target.png"}"
Or you can remove them before you deserialize:
[urlString substringWithRange:NSMakeRange(1, [urlString length]-2)]

Parse double quotes and single quotes in Json Parsing

I am parsing a JSON url. I am getting \u00e2\u20ac\u0153 instead of single quotes and \u00e2\u20ac\u009d instead of double quotes. On my end i am doing NSUTF8StringEncoding but still not getting single and double quotes.
Here is the response in the web browser:
{"status":"1","data":[{"id":"1345","title_en":"","content_en":"Mom
said, \u00e2\u20ac\u0153I love this one.\u00e2\u20ac\u009d\n\nJake
said, \u00e2\u20ac\u0153I don\u00e2\u20ac\u2122t get
it.\u00e2\u20ac\u009d\n","image":"1396","pos":"2","video_type":"0","video":"0","video_alt":"","sound_type":"1","sound":"1123","sound_alt":"","author":"","type":"0","book_id":"148","user_id":"24","title":"The
Art
Museum","author_url":"maureen-d-1","book_url":"the-art-museum","video_filename":"","sound_filename":"atmuseum2.m4a"}]}
Is it possible to parse above response using NSUTF8StringEncoding or something else. Or i need to get it done from php side.
Do you use NSJSONSerialization? In my app i do this:
NSError* localError;
id jsonObjects = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&localError];
In "data" variable i have response from server. I receiving UTF-encoded text from server too (like \u00e2\u20ac) but finally i get normal string. "jsonObjects" will contain data in native types:
if ([jsonObjects isKindOfClass:[NSDictionary class]])
{
NSNumber* age = [jsonObjects objectForKey:#"age"];
//...etc
}

Resources