1

I am getting the below string n cookies from a UIWebview which is javascript escaped.

"%7B%27status%27%20%3A%20400%2C%20%27message%27%20%3A%20%27%u30C6%u30B9%u30C8%u30E1%u30C3%u30BB%u30FC%u30B8%27"

I am using the below function to get unescaped string.

NSString *decodeString = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
decodeString = [decodeString stringByReplacingOccurrencesOfString:@""" withString:@"\""];

The expected output is

"{'status' : 400, 'message' : 'テストメッセージ'}"

but *decodeString is coming as nil

What is the proper way to decode.

Thanks.

  • have a look at this => http://stackoverflow.com/a/10691541/1155650 – Rohit Vipin Mathews Aug 04 '15 at 06:22
  • I tried this. But I am getting null. – Leena Patel Aug 04 '15 at 06:32
  • @LeenaPatel when i tested it with `"%7B%27status%27%20%3A%20400%2C%20%27message%27%20%3A%20%27"` string means before %u ....it works fine...but when I add the string after %u it give nil...means problem is `%u30B9%u30C8%u30E1%u30C3%u30BB%u30FC%u30B` data – Bhavin Bhadani Aug 04 '15 at 07:02
  • @Bhavin while sending the japanese message from server side, "テストメッセージ" is converting to "%u30C6%u30B9%u30C8%u30E1%u30C3%u30BB%u30FC%u30B8" and After that its doing UTF8 encoding. – Leena Patel Aug 04 '15 at 07:19
  • Yes . If message will be in english, I am able to decode it using NSUTF8Encoding. But for Japanese message, Its giving nil. – Leena Patel Aug 04 '15 at 07:27

1 Answers1

0

My first quick solution is separe utf charts and unicode charts, like this:

NSString *string = @"%7B%27status%27%20%3A%20400%2C%20%27message%27%20%3A%20%27%u30C6%u30B9%u30C8%u30E1%u30C3%u30BB%u30FC%u30B8%27";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"%27message%27(.*)%27" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
NSLog(@"%@", modifiedString);

NSString *decodeString = [modifiedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", decodeString);

Better will be use this:

NSString *str = @"%7B%27status%27%20%3A%20400%2C%20%27message%27%20%3A%20%27%u30C6%u30B9%u30C8%u30E1%u30C3%u30BB%u30FC%u30B8%27";
str = [str stringByReplacingOccurrencesOfString:@"%u" withString:@"\\u"];
NSString *convertedStr = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",convertedStr);

in this case is output:

{'status' : 400, 'message' : '\u30C6\u30B9\u30C8\u30E1\u30C3\u30BB\u30FC\u30B8' 

in this case you must procees unicode charts .... i hope this help.

Jiri Zachar
  • 487
  • 3
  • 8