【问题标题】:Parse nsstring json valuses in iphone?在iphone中解析字符串json值?
【发布时间】:2012-07-04 10:27:34
【问题描述】:

我在 NSString 中有 JSon 值。我正在尝试解析来自 NSString JSonValue 的值。

NSString 值如:

result =  [{"no":"01","send":"2010-05-03 01:26:48","from":"0000000000","to":"1111111111","text":"abcd"}]

我已经尝试使用下面的代码来解析值 no、send、from、to、text。

    NSString *jsonString = result;
    NSDictionary *jsonArray = [jsonString jsonValue]; //Am trying to save the values from NSString to NSDictionary the app getting crash here.
    NSLog(@"JsonDic : %@", jsonArray);

谁能帮忙解析来自 NSString 的 JSon 值?提前致谢。

【问题讨论】:

  • 所以你搜索了stackoverflow并没有找到任何关于如何在iOS上解析JSON的问题?很奇怪……

标签: iphone ios json parsing nsstring


【解决方案1】:

对于iOS5,您可以使用NSJSONSerialization

NSError *error;
NSString *json = @"[{\"no\":\"01\",\"send\":\"2010-05-03 01:26:48\",\"from\":\"0000000000\",\"to\":\"1111111111\",\"text\":\"abcd\"}]";
id jsonObj = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];

你也可以使用SBJson

【讨论】:

  • 感谢您的回复。我已经解决了这个问题,我可以得到值。感谢您的帮助。
【解决方案2】:

戈皮纳特。我已经提到了代码,请试试这个。我已经测试了我可以得到否。

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

NSDictionary *jsonArray = (NSDictionary *) [parser objectWithString:result error:nil];  
NSLog(@"jsonArray : %@", jsonArray);

NSArray *depositArray = [jsonArray valueForKey:@"no"];
NSLog(@"depositArray : %@", depositArray);

如果您遇到任何问题,请进行测试并告诉我。谢谢。

【讨论】:

    【解决方案3】:

    解析 JSON 有点复杂。

    就我而言,我使用的是 SBJSON,你可以从这里下载它:http://stig.github.com/json-framework/

    这是一组简单的文件,可以放入您的项目中。我建议成立一个专门的小组。

    完成此操作后,您可以使用以下代码:

    NSError *jsonError;
    NSDictionary *jsonResults;
    
    SBJsonParser* parser = [[SBJsonParser alloc]init];
    jsonResults = [parser objectWithString:YOURSTRING error:&jsonError ];
    
    if (jsonResults == nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"Something bad happened with JSON : %@ : %@",YOURSTRING,[ jsonError localizedDescription ]] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    } else {   
       NSLog(@"JSON result : %@",jsonResults);
    
    }
    

    如果您需要更多信息,可以在 SBJSon 上找到很好的教程,例如:http://www.touch-code-magazine.com/tutorial-fetch-and-parse-json/

    【讨论】:

      猜你喜欢
      • 2011-10-27
      • 2018-04-13
      • 2016-08-15
      • 2019-11-27
      • 2018-09-18
      • 2012-08-06
      • 2011-07-21
      • 2019-05-07
      相关资源
      最近更新 更多