iOS中的JSON解析错误
我正在尝试解析json响应(我从SOAPWebService响应的结果标记获得),如图所示,并带有以下行iOS中的JSON解析错误,ios,json,web-services,soap,Ios,Json,Web Services,Soap,我正在尝试解析json响应(我从SOAPWebService响应的结果标记获得),如图所示,并带有以下行 NSString *soapMessage = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-insta
NSString *soapMessage = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<GetPhotoSession xmlns=\"http://tempuri.org/\">"
"<UserID>%@</UserID>"
"<photoSessionID>%@</photoSessionID>"
"</GetPhotoSession>"
"</soap:Body>"
"</soap:Envelope>",[HelperClass retrieveStringForKey:kUserID],self.currentSession.sessionID];
NSURL *url = [NSURL URLWithString:kBaseURL];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%lu", (unsigned long)[soapMessage length]];
[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[theRequest addValue: @"http://tempuri.org/GetPhotoSession" forHTTPHeaderField:@"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection ) {
self.webResponseData = [NSMutableData data];
}else {
NSLog(@"Some error occurred in Connection");
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.webResponseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.webResponseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Some error in your Connection. Please try again.");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Received Bytes from server: %d", [self.webResponseData length]);
NSString *myXMLResponse = [[NSString alloc] initWithBytes: [self.webResponseData bytes] length:[self.webResponseData length] encoding:NSUTF8StringEncoding];
NSLog(@"%@",myXMLResponse);
NSError *errorPointer;
NSDictionary *dict = [XMLReader dictionaryForXMLString:myXMLResponse error:&errorPointer];
NSString *jsonData = dict[@"soap:Envelope"][@"soap:Body"][@"GetPhotoSessionResponse"][@"GetPhotoSessionResult"][@"text"];
NSData *data = [jsonData dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&errorPointer];
NSLog(@"%@",[json objectForKey:@"Head"]);
}
NSString*soapMessage=[NSString stringWithFormat:@]
""
""
""
"%@"
"%@"
""
""
“”,[HelperClass retrieveStringForKey:kUserID],self.currentSession.sessionID];
NSURL*url=[NSURL URLWithString:kBaseURL];
NSMutableURLRequest*theRequest=[NSMutableUrlRequestWithURL:url];
NSString*msgLength=[NSString stringWithFormat:@“%lu”,无符号长)[soapMessage长度]];
[theRequest addValue:@“text/xml;charset=utf-8”用于HttpHeaderField:@“Content Type”];
[请求附加值:@”http://tempuri.org/GetPhotoSessionforHTTPHeaderField:@“SOAPAction”];
[theRequest addValue:msgLength for HttpHeaderField:@“内容长度”];
[TheRequestSetHttpMethod:@“POST”];
[TheRequestSetHttpBody:[soapMessage数据使用编码:NSUTF8StringEncoding];
NSURLConnection*连接=[[NSURLConnection alloc]initWithRequest:theRequest委托:self];
if(连接){
self.webResponseData=[NSMutableData];
}否则{
NSLog(@“连接中发生了一些错误”);
}
-(void)连接:(NSURLConnection*)连接DidReceiverResponse:(NSURResponse*)响应{
[self.webResponseData setLength:0];
}
-(void)连接:(NSURLConnection*)连接didReceiveData:(NSData*)数据{
[self.webResponseData-appendData:data];
}
-(无效)连接:(NSURLConnection*)连接失败错误:(NSError*)错误{
NSLog(@“您的连接有错误,请再试一次。”);
}
-(无效)连接IDFinishLoading:(NSURLConnection*)连接{
NSLog(@“从服务器接收的字节数:%d”,[self.webResponseData length]);
NSString*myXMLResponse=[[NSString alloc]initWithBytes:[self.webResponseData bytes]长度:[self.webResponseData length]编码:NSUTF8StringEncoding];
NSLog(@“%@”,myXMLResponse);
n错误*错误指针;
NSDictionary*dict=[XMLReader dictionaryForXMLString:myXMLResponse错误:&errorPointer];
NSString*jsonData=dict[@“soap:Envelope”][@“soap:Body”][@“GetPhotoSessionResponse”][@“GetPhotoSessionResult”][@“text”];
NSData*data=[jsonData dataUsingEncoding:NSUTF8StringEncoding];
id json=[NSJSONSerialization JSONObjectWithData:数据选项:0错误:&错误指针];
NSLog(@“%@,[json objectForKey:@“Head]”);
}
但我在“json”对象中得到了零。下面是JSON响应的pastie链接。以下是错误指针的说明
错误指针的打印说明:
Error Domain=NSCOCAERRORDOMAIN Code=3840“操作无法完成。(可可错误3840)。“(JSON文本未以数组或对象开头,允许未设置片段的选项。)UserInfo=0x7d0156a0{NSDebugDescription=JSON文本未以数组或对象开头,允许未设置片段的选项。}这是您自己的web服务还是现有的web服务?如果这是您自己的,您确定您的JSON实际上是正确的吗 我认为问题在于:
"ImageBase64Data": "/9j/4AAQSkZJRgABAQA .... blah blah ==
"
注意这里的关键点。最后的双引号在下一行。应该是
"ImageBase64Data": "/9j/4AAQSkZJRgABAQA .... blah blah =="
为了便于将来参考,在问题中剪切并粘贴JSON有效负载文本比显示图像容易得多
因此,从这里获取您的数据:
我已经运行了以下代码:
NSError *error = nil;
NSString *path = [[NSBundle mainBundle] pathForResource:@"badjson" ofType:@"txt"];
NSString *jsonStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
// jsonStr = [[jsonStr componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@""];
NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSLog(@"Error is %@", error);
NSLog(@"JSON is %@", json);
注意,我现在有一行注释掉了。当我这样做时,它失败了。但是,失败与上面列出的不同。我明白了
错误是错误域=NSCOCAERRORDOMAIN代码=3840“操作
无法完成。(Cocoa错误3840。)(未替换控件
字符120周围的字符。)UserInfo=0x7f9519f71510
{NSDebugDescription=字符120周围的未替换控制字符。}
如果我取消注释那一行,它就会工作。仅显示输出的一个片段:
2014-12-26 12:03:35.020 Sample[49732:6379864] Error is (null)
2014-12-26 12:03:35.022 Sample[49732:6379864] JSON is {
Head = (
{
ID = 1092;
ImageBase64Data = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDACAWGBwYFCAcGhwkIiAmMFA0MCwsMGJGSjpQdGZ6eHJmcG6AkLicgIiuim5woNqirr7EztDOfJri8uDI8LjKzsb/
您的数据使用base64输出,该输出使用换行符来分隔每个编码行。这就是为什么您会在结尾看到如下文本:
==
","ImageName"
您还会注意到Base64中的绝大多数线条看起来都是统一的。。因为这个划界
使用此选项去掉换行符(您需要为您的代码修改它)
如果这不起作用,那么您需要提供更多信息:
-是否从Xcode控制台获取输出?
-在NSLog存在的地方添加代码以获取输出(如果没有,请添加一个)。
-添加NSLog后,提供该输出
虽然看起来你“已经提供了信息”,但显然在信息方面存在差距。否则,我希望看到相同的N错误输出。因此,我们要么缺少步骤,要么可能存在其他差异。例如,我在iOS8模拟器中运行这个。这并不重要,但总有一种可能性,即您运行的iOS版本较旧,对JSON的解析方式不同。粘贴JSON,并检查其是否有效JSONLINT的结果:第5行的解析错误:。。。“ImageBase64Data”:“/9j/4AAQSkZJRgABAQA-------------------------------------^应为
ImageBase64Data
键的'STRING','NUMBER','NULL','TRUE','FALSE','{','['值无效,请检查是否有换行符或”中间value@Rob不。这是标记的值,它是一个JSON响应OK。我之所以这么做是因为您报告了错误消息(“JSON文本不是以数组或对象开头的…”)与传递给NSJSONSerialization
的非JSON更为一致,而不是Midhun/Zaph所追求的,即它是JSON,但在某种程度上是错误的。通常错误的JSON会给出更具描述性的错误。您的错误表明一个更根本的问题。我可能建议数据的NSLog
(应以十六进制显示)以便我们可以确认
jsonStr = [[jsonStr componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@""];