Convert NSString to NSDictionary bug - ios

I have a string from server, and when i try to convert it to NSDictionary - i get "nil". When i try to write same NSString by myself - it's ok!
I get from server encoded string, then i use "AES256DecryptWithKey" from NSString+AESCrypt.h to decrypt, and get NSString, this string i convert to NSData and then try to get NSDictionary
NSString *str = #"{\"error\":{\"password\":[\"Error wrong!\"]}}"; //string written by myself
NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData
options:kNilOptions
error:&error];
This code work, but then i get this string from server - not(
NSData log (message from server) - <7b226572 726f7222 3a7b2270 61737377 6f726422 3a5b22d0 9dd0b5d0 bfd180d0 b0d0b2d0 b8d0bbd1 8cd0bdd1 8bd0b920 656d6169 6c20d0b8 d0bbd0b8 20d0bfd0 b0d180d0 bed0bbd1 8c225d7d 7d000000>
NSData log (my string) - <7b226572 726f7222 3a7b2270 61737377 6f726422 3a5b22d0 9dd0b5d0 bfd180d0 b0d0b2d0 b8d0bbd1 8cd0bdd1 8bd0b920 656d6169 6c20d0b8 d0bbd0b8 20d0bfd0 b0d180d0 bed0bbd1 8c225d7d 7d>
If i NSLog string from server, it - {"error":{"password":["Error wrong!"]}} , string without "\"
Then i "po &error.localizedDescription" -
error: address of property expression requested
error: 1 errors parsing expression
Then i "po error.localizedDescription" - Printing description of error:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x7f9940497550 {NSDebugDescription=Garbage at end.}
What it can be??

The error message says:
Garbage at end.
So, comparing your data and the data from the server, we see:
Test string data:
<7b226572 726f7222 3a7b2270 61737377
6f726422 3a5b22d0 9dd0b5d0 bfd180d0
b0d0b2d0 b8d0bbd1 8cd0bdd1 8bd0b920
656d6169 6c20d0b8 d0bbd0b8 20d0bfd0
b0d180d0 bed0bbd1 8c225d7d 7d>
Server data:
<7b226572 726f7222 3a7b2270 61737377
6f726422 3a5b22d0 9dd0b5d0 bfd180d0
b0d0b2d0 b8d0bbd1 8cd0bdd1 8bd0b920
656d6169 6c20d0b8 d0bbd0b8 20d0bfd0
b0d180d0 bed0bbd1 8c225d7d 7d000000>
The decoded data is 3 bytes longer. Maybe it is padded ahead of the encryption or as an effect of your decryption due to some padding parameter. As a workaround you could remove the stray 000000.

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.

Q:iOS characters convert to gbk encoding ,then convert to hex, then to data

In my project with BLE develop.
I have to write hex data to peripheral,
but now I have a chinese string:
NSString *originStr = #"PJ1";
But the demo is that:
Byte b = 0X01; // ER: 4552 PJ1:504A31CED2B0AEC1CEC2EDB6F9
NSData *data = [NSData dataWithBytes:&b length:sizeof(b)];
[self.currPeripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
Now my problem is how to convert my #"PJ1" to the data in demo.
Thanks Larme's hint,and I use this function to get data:
NSString *dataStr = writeStr;
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingG‌​‌​B_18030_2000); NSData *myData = [dataStr dataUsingEncoding:enc];
And I use the below to write info to development board:
[self.currPeripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicPropertyWrite];
Please Attention: the type is not the question's demo: CBCharacteristicWriteWithResponse but the type:CBCharacteristicPropertyWrite.
Or it will cause the error:
Error Domain=CBATTErrorDomain Code=3 "Writing is not permitted." UserInfo={NSLocalizedDescription=Writing is not permitted.} . And I also thanks Larme's hint again.

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)]

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

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)

Resources