从网页读取字符串

时间:2011-07-10 01:21:07

标签: iphone ios cocoa-touch

我已经对堆栈溢出进行了很多调查,发现了一些可能适合我想做的事情,但我不会撒谎,我有点迷失。我有一个非常简单的字符串,显示在我想要读入应用程序的网页上,解析它,然后在一些UITextFields中显示它。网址为mtgox.com/data/code/ticker.php。这是一个php页面,它产生一个简单的JSON字符串,一个单行,如下所示:

{"ticker":{"high":14.6999,"low":14.04,"avg":14.379509781,"vol":10981,"last":14.44278,"buy":14.4302,"sell":14.44278}}

如何将此字符串读入我的应用程序然后解析它?我在考虑可能在网站上使用UIWebView类和stringByEvaluatingJavaScriptString方法,但我对javascript知之甚少,也不知道这是否有效。

我见过一些人提到使用JSON库,但不知道这对我需要的东西是否最好,如果这样做会有效;我觉得这可能有点过分,因为我只解析了一行。

2 个答案:

答案 0 :(得分:2)

我建议您浏览this tutorial,它应该向您展示从网页获取JSON编码信息并解析它需要了解的内容。

答案 1 :(得分:0)

如果你坚持不使用JSON解析器(库安装和其他框架配置hasle),那么 下面的代码已经过测试,可以正常使用您的网址:

将此代码放在具有文本字段的视图控制器中。


- (NSDictionary *)parseJSONFromSomeURL
{
    NSURL *pageURL = [NSURL URLWithString:@"http://mtgox.com/code/data/ticker.php"];
    NSString *JSONString = [NSString stringWithContentsOfURL:pageURL encoding:NSUTF8StringEncoding error:nil];

    JSONString = [JSONString stringByReplacingOccurrencesOfString:@"{" withString:@""];
    JSONString = [JSONString stringByReplacingOccurrencesOfString:@"}" withString:@""];
    JSONString = [JSONString stringByReplacingOccurrencesOfString:@"\"" withString:@""];

    NSArray *components = [JSONString componentsSeparatedByString:@","];

    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    for (NSString *parts in components)
    {
        NSArray *subComponents = [parts componentsSeparatedByString:@":"];
        // First element has 3 items (it has ticker)
        if ([subComponents count] > 2)
        {
            [result setValue:@"" forKey:[subComponents objectAtIndex:0]];
            [result setValue:[subComponents objectAtIndex:2] forKey:[subComponents objectAtIndex:1]];
        }
        else
        {
            [result setValue:[subComponents objectAtIndex:1] forKey:[subComponents objectAtIndex:0]];
        }
    }

    return result;
}

希望它有助于解决您的问题。