【问题标题】:Returning NSString instead of NSDictionary返回 NSString 而不是 NSDictionary
【发布时间】:2013-05-24 14:35:30
【问题描述】:

我正在使用一种方法来调用 Web 服务并在服务器上上传转录音频文件。方法如下:

    - (NSDictionary *)UploadTranscriptionAudio:(NSString *)uploadfor forPN_ID:(NSString 
   *)pn_id forTaskFlag:(NSString *)taskflag documentPath:(NSString *)documentpath 
    forUserName:(NSString *)username file_path_msd:(NSString *)file_path_msd 
   audioFilePath:(NSString *)audiofilepath{

NSDictionary *response = nil;


NSURL * url = [NSURL URLWithString:[AppDelegate sharedInstance].str_webServiceUrl];

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

[request setPostValue:uploadfor forKey:@"Uploadfor"];
[request setPostValue:pn_id forKey:@"PNID"];
[request setPostValue:taskflag forKey:@"task_flag"];
[request setPostValue:documentpath forKey:@"Path"];
[request setPostValue:username forKey:@"Username"];
[request setPostValue:file_path_msd forKey:@"file_path_msd"];
[request setFile:audiofilepath forKey:@"uploadedfile"];

[request startSynchronous];

NSError *error = [request error];
if (!error) {
    response = (NSDictionary*)[request responseString];
    NSLog(@"Response = %@",response);
    return response;
}
return response;

}

这个方法仍然返回一个 NSstring 作为响应。我想要的是这个方法应该给我一个 NSDictionary。因为我必须在其他地方使用该字典中键的值。有人可以帮我解决这个问题。

【问题讨论】:

  • 它是 JSON 字符串吗?应该如何转换?
  • [request responseString] 的调用返回NSString。将其转换为 NSDictionary 不会神奇地转换它。它仍然是NSString。您需要解析字符串并根据解析结果创建字典。
  • 谢谢! rmaddy,但你能用一些代码告诉我如何解析那个字符串吗?
  • 在你的问题中编辑你得到的字符串的一个可能 100 个字符的样本,这样我们就可以看到它是否是 JSON(可能是这种情况)。
  • (这里有 200 个线程介绍如何在 iOS 中解析 JSON。)

标签: ios json asiformdatarequest


【解决方案1】:

你好 shikher maddy 说对了,你可以按如下方式解析字符串

if (responseString == NULL) {
    // do something u want
} else {
    NSDictionary *jsonResponse = [responseString JSONValue];
    NSLog(@"  %@",jsonResponse);
}

【讨论】:

  • 我们不知道结果是JSON。 OP 还没有提出这样的要求。
  • 这是我得到的响应字符串,当然 ii 是 JSON。 Response = {"code":"1","description":"文件上传成功","file":"IMSEMROH_7674.caf","file_msd":"IMSEMROH_7674"}
  • 另外,JSONValue 不是 NSString 的标准方法。它是某个第 3 方框架添加的类别吗?如果是这样,它需要用链接说明这是什么。
【解决方案2】:

如果我是你,我会像这样使用SBJSONParser

SBJsonParser *parser=  [[SBJsonParser alloc] init];

NSDictionary *dictionnary = [parser objectWithString:responseString error:nil];

【讨论】:

  • 我使用了你的方法,但它是说 SBJsonparser 可能不会响应 objectWithString:error 方法。我现在该怎么办?
  • 你添加了#import "JSON.h" 吗?
猜你喜欢
  • 1970-01-01
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
相关资源
最近更新 更多