json 将 NSString 转换为 NSData - [NSString dataUsingEncoding] 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9966953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:15:52  来源:igfitidea点击:

converting NSString to NSData - [NSString dataUsingEncoding] exception

iphonejsonios5nsdata

提问by Fury

I was converting NSString to NSData in order to parse by JSON, but I got the following error.

我正在将 NSString 转换为 NSData 以便通过 JSON 进行解析,但出现以下错误。

Terminating app due to uncaught exception 'NSInvalidArgumentException', 
  reason: '-  [__NSCFDictionary dataUsingEncoding:]: 
  unrecognized   selector sent to instance 0x7987d60'

The code is as followings:

代码如下:

NSData *data = [str dataUsingEncoding:NSASCIIStringEncoding]; 
//NSUTF8StringEncoding also failed.
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

In my opinion, this is because str contains new-line character:'\n'.

在我看来,这是因为 str 包含换行符:'\n'。

Am I correct?

我对么?

Would somebody please help me to solve this problem?

有人可以帮我解决这个问题吗?

回答by jmstone617

Your error says that you are trying to send dataUsingEncoding:allowLossyConversion:to an instance of NSDictionary, which doesn't know what to do with that selector. Make sure your strobject is actually a string...

您的错误表明您正在尝试发送dataUsingEncoding:allowLossyConversion:到 的实例NSDictionary,该实例不知道如何处理该选择器。确保您的str对象实际上是一个字符串...

回答by Fernando Cervantes

Try using NSUnicodeStringEncodinginstead of NSASCIIStringEncoding. So replace the line:

尝试使用NSUnicodeStringEncoding代替NSASCIIStringEncoding. 所以替换该行:

NSData *data = [str dataUsingEncoding:NSASCIIStringEncoding]; 

with this:

有了这个:

NSData *data = [str dataUsingEncoding:NSUnicodeStringEncoding]; 

回答by Praveen-K

I just checked with my sample string. **If you could have given me your string then i could have checked out with my following sample code.

我刚刚检查了我的示例字符串。**如果您可以给我您的字符串,那么我可以使用以下示例代码进行检查。

NSString *msg = [NSString stringWithFormat:@"tell me \"where\"\n"
                  "is\n"
                  "wrong"];
NSData *theData = [msg dataUsingEncoding:NSASCIIStringEncoding];
NSString* theString = [[NSString alloc] initWithData:theData encoding:NSASCIIStringEncoding];

BOOL isValid = [NSJSONSerialization isValidJSONObject:theString];
NSLog(@"Value %d %@",isValid, theString);

For me The value is coming 0 and tell me "where"

对我来说 值即将变为 0 并告诉我“在哪里”

is

wrong

错误的