1

我正在使用 touch 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
4

2 回答 2

0

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

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

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

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

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

于 2010-08-02T07:40:46.143 回答
0

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

所以希望你在 twitterTrends 中有一个 NSDictionaries 的 NSArray。要获取零件,只需枚举数组。

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

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

[[twitterTrends objectAtIndex:5] objectForKey:@"url"];
于 2010-08-02T07:44:57.350 回答