【问题标题】:ios array to dictionary or to arrayios数组到字典或数组
【发布时间】:2011-11-07 13:47:34
【问题描述】:

我收到对我的应用程序 [Twitter 网络服务] 的 JSON 响应,它是一个字符串,但例如索引 0 处的对象是:

es array en:0, tiene {
contributors = "<null>";
coordinates = "<null>";
"created_at" = "Thu Aug 04 23:26:05 +0000 2011";
favorited = 0;
geo = "<null>";
id = 99259843982016513;
"id_str" = 99259843982016513;
"in_reply_to_screen_name" = "<null>";
"in_reply_to_status_id" = "<null>";
"in_reply_to_status_id_str" = "<null>";
"in_reply_to_user_id" = "<null>";
"in_reply_to_user_id_str" = "<null>";
place = "<null>";
"possibly_sensitive" = 0;
"retweet_count" = 0;
retweeted = 0;
source = "<a href=\"http://twitter.com/tweetbutton\" rel=\"nofollow\">Tweet Button</a>";
text = "Stack Exchange Q&A site proposal: Freelance Workers http://t.co/yaW1RHp";
truncated = 0;
user =     {
    "contributors_enabled" = 0;
    "created_at" = "Mon Jul 13 19:39:31 +0000 2009";
    "default_profile" = 0;
    "default_profile_image" = 0;
    description = "My goal is to enable the brain computer interfaces to use the possibilities of mobile platforms for robotics and physical computing";
    "favourites_count" = 0;
    "follow_request_sent" = "<null>";
    "followers_count" = 92; ...

所以我的数组 [对于每个 twitt] 大约有 17 个对象,那么我如何将这些对象分解为更多的数组或字典?

我特别想要文本键

text = "Apple vs Samsung tablets [haha and Samsung is an Apple hardware provider!!]\nhttp://t.co/rvv43Hy";

非常感谢

【问题讨论】:

  • (第一个)“文本”值很容易,因为它在外部字典中。只需使用objectForKey:@"text"。 (但您为“文本”显示了不同的值,因此它可能是更深入的嵌入版本。)

标签: ios arrays json dictionary


【解决方案1】:

可能已经为此构建了一个解析器,但如果没有,我认为您会发现以下方法很有用。

NSArray *strings = [input componentsSeparatedByString:@";"];

它返回一个带有(在这种情况下)“;”的字符串数组作为分隔符。

{贡献者 = "" , 坐标 = "", ...}

您可以将它们进一步分开:

NSDictionary *dict = [NSDictionary dictionary];
for (NSString *s in strings)
{
    NSArray *keyValue = [s componentsSeparatedByString:@"="];
    NSString *key = [keyValue objectAtIndex:0];
    NSString *value = [keyValue objectAtIndex:1];
    [dict setValue:value forKey:key];
}

在响应的开头似乎确实有一些额外的数据,您可能必须先将其去掉。

【讨论】:

  • OP 的数据是一个包含另一个 NSDictionary 的 NSDictionary。尝试使用 componentsSeparateByStrings 解析它是他愚蠢的高度。
【解决方案2】:

例如,您可以从外部字典中提取“用户”对象并将其分配给 NSDictionary 变量。然后,您可以从第二个字典中提取“default_profile”。

人们可能会编写一个简单的“路径导航器”工具,该工具可以通过“路径符号”访问单个实体,而无需显式提取组件,但我不知道“罐头”工具。

【讨论】:

    【解决方案3】:

    以防万一其他人正在寻找这个,我最终使用了

    Stig Brautaset 的开源 JSON 框架。 用它的解析器, 并遵循一些指令 from here

    【讨论】:

      猜你喜欢
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多