我如何获得名称和价值的价值?来自nsdictionary对象的url?

时间:2010-08-02 05:49:13

标签: iphone xcode nsdictionary touchjson

我正在使用触控JSON,这对我来说非常好。我能够获取一个数组,将其放入字典中,通过touchJSON序列化并通过http发送出去。

现在在返回端,我收到了数据,并将其放入字典中(我使用来自twitter的trends.json作为示例JSON)。

如果我试图从字典对象中获取趋势值,我会得到:

2010-08-02 00:23:31.069 rateMyTaxi[30610:207] ANSWER: (
  {
    name = "Fried Chicken Flu";
    url = "http://search.twitter.com/search?q=Fried+Chicken+Flu";
  },
  {
    name = "Lisa Simpson";
    url = "http://search.twitter.com/search?q=Lisa+Simpson";
  },
  {
    name = "#breakuplines";
    url = "http://search.twitter.com/search?q=%23breakuplines";
  },
  {
    name = "#thingsuglypeopledo";
    url = "http://search.twitter.com/search?q=%23thingsuglypeopledo";
  },
  {
    name = "Inception";
    url = "http://search.twitter.com/search?q=Inception";
  },
  {
    name = "#sharkweek";
    url = "http://search.twitter.com/search?q=%23sharkweek";
  },
  {
    name = "JailbreakMe";
    url = "http://search.twitter.com/search?q=JailbreakMe";
  },
  {
    name = "Kourtney";
    url = "http://search.twitter.com/search?q=Kourtney";
  },
  {
    name = "Shark";
    url = "http://search.twitter.com/search?q=Shark";
  },
  {
    name = "Boondocks";
    url = "http://search.twitter.com/search?q=Boondocks";
  }
)

如果我尝试获取名称或URL的值,我什么都没有,这是令人沮丧的。这就是我需要的数据。你可以告诉它是一种字典格式,因为它是格式化的,它正在正确地读取趋势。我很确定我错过了什么,所以请让我知道要遵循的方向。

以下是代码:

// this is all touch JSON magic. responseString has the full contents of trends.json

 NSString *response = [request responseString];
 NSLog(@"response value is:%@",response);

 NSString *jsonString = response;
 NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding];
 NSError *error = nil;
 NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
//end of touchJSON.  It is in a dictionary now.

 NSLog(@"dictionary:%@, error %@", dictionary, error); //http://cl.ly/adb6c6a974c3e70fb51c

 NSString *twitterTrends = (NSString *) [dictionary objectForKey:@"trends"];
 NSLog(@"ANSWER:%@",twitterTrends); //http://cl.ly/fe270fe7f05a0ea8d478

2 个答案:

答案 0 :(得分:0)

你只能提取词典数组。 (响应在字典内的数组中有一个字典。)

您需要从数组中提取每个字典,然后查找该字典中的名称和URL条目。

这样的东西应该打印第一个条目:

NSArray *twitterTrends = [dictionary objectForKey:@"trends"];
NSDictionary *entry1 = [twitterTrends objectAtIndex:0];
NSLog(@"entry1: %@, %@", [entry1 objectForKey:@"name"], [entry1 objectForKey:@"url"]);

(代码尚未经过测试,因此可能无法直接编译!)

答案 1 :(得分:0)

当您使用格式字符串%@打印对象时,您将获得发送到对象的描述消息的输出。对于NSDictionary,此输出看起来非常类似于未解析的JSON,但它不是字符串,它是NSDictionaries,NSArrays,NSStrings,NSNumbers和NSDates的对象图。

所以希望你在twitterTrends中有NSArray的NSDiction。获取部件只是枚举数组。

for (NSDictionary* trend in twitterTrends) {
    NSString* url = [trend objectForKey:@"url"];
    NSString* name = [trend objectForKey:@"name"];
}

或者您可以通过索引访问趋势:

[[twitterTrends objectAtIndex:5] objectForKey:@"url"];