2011-10-20 76 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字符串,但是你的帖子真的很有幫助!非常感謝! –