2011-10-20 9 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の「コンテンツ」を抽出するようなエントリの配列を与えます。私はログに係る__NSArrayMあるresponseDataDictにobjectForKey送信する場合のNSLogがエラーを吐き出す

- (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; 
    } 
} 

}

私はここで何が間違っていましたか?

+0

使用しているJSONパーサーが可変コレクションを返すのですか? –

答えて

1

NSMutableDictionary * responseDataDict = [JSONval objectForKey:@ "用語"];

ただし、"terms"の値は辞書ではありません。それは配列です。 JSON文字列の角括弧に注意してください。代わりに、

をご使用ください。

配列の各用語は、対応する値(オブジェクト)が別のオブジェクト(辞書)である単一の名前(キー)を含むオブジェクト(辞書)です。

// 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文字列をどのように分解するべきか明確ではありませんでしたが、あなたの投稿は本当に役立ちます!どうもありがとう! –