2011-10-20 73 views
1

对于我的项目,我使用PHP构建了自己的api。 JSON编码的结果基本上是给我的条目类似下面使用Objective-C解析JSON

{"terms":[ 
      {"term0": 
       {"content":"test id", 
       "userid":"100","translateto":null, 
       "hastranslation":"0", 
       "created":"2011-10-19 16:54:57", 
       "updated":"2011-10-19 16:55:58"} 
       }, 
      {"term1": 
       {"content":"Initial content", 
       "userid":"3","translateto":null, 
       "hastranslation":"0", 
       "created":"2011-10-19 16:51:33", 
       "updated":"2011-10-19 16:51:33" 
       } 
      } 
     ] 
} 

不过,我一直在用的NSMutableDictionary工作问题和Objective-C中提取的“内容”的数组。

- (void) connectionDidFinishLoading:(NSURLConnection *)connection { 
[connection release]; 

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
[responseData release]; 
NSMutableDictionary *JSONval = [responseString JSONValue]; 
[responseString release]; 

if (JSONval != nil) { 
    NSMutableDictionary *responseDataDict = [JSONval objectForKey:@"terms"]; 
    if (responseDataDict!= nil) { 
     for (id key in responseDataDict) { 
      NSString *content = [[responseDataDict objectForKey:key]objectForKey:@"content"]; 
      [terms addObject:content]; 
      textView.text = [textView.text stringByAppendingFormat:@"\n%@", content]; 
     } 
     button.enabled = YES; 
    } 
} 

}

哪里的NSLog吐出了错误,当我送objectForKey到responseDataDict,这是根据日志__NSArrayM。

我在这里做错了什么?

+0

你确定你使用的JSON解析器返回可变集合吗? – 2011-10-20 06:49:15

回答

1

的NSMutableDictionary * responseDataDict = [JSONval objectForKey:@ “术语”];

"terms"的值不是字典;这是一个数组。请注意JSON字符串中的方括号。您应该使用:

NSArray *terms = [JSONval objectForKey:@"terms"]; 

改为。

请注意,数组中的每个项是包含单个名称(键)的对象(键),其对应的值(对象)依次为另一个对象(字典)。您应该将它们解析为:

// JSONval is a dictionary containing a single key called 'terms' 
NSArray *terms = [JSONval objectForKey:@"terms"]; 

// Each element in the array is a dictionary with a single key 
// representing a term identifier 
for (NSDictionary *termId in terms) { 
    // Get the single dictionary in each termId dictionary 
    NSArray *values = [termId allValues]; 

    // Make sure there's exactly one dictionary inside termId 
    if ([values count] == 1) { 
     // Get the single dictionary inside termId 
     NSDictionary *term = [values objectAtIndex:0]; 

     NSString *content = [term objectForKey:@"content"] 
     … 
    } 
} 

根据需要添加进一步验证。

+0

这就是诀窍!我不清楚我应该如何分解JSON字符串,但是你的帖子真的很有帮助!非常感谢! –