0

こんにちは、Web サービスの json 文字列を作成しました。名前と説明を出力して NSLog に表示したいと考えています。どうやってやるの。これまでの私のコードは次のとおりです。

    dic = [NSJSONSerialization JSONObjectWithData:result options:kNilOptions error:nil];


NSLog(@"Results %@",[NSString stringWithFormat:@"%@",[[dic objectForKey:@"d"]objectForKey:@"Name"]]);

私はこのエラーが発生します:

-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x6b50f30

辞書に NSLog を作成すると、次のようになります。

{
d = "{
\n  \"Name\": \"Apple\",
\n  \"Beschreibung\": \"Steve Jobs ist tot\"}";
}

私の json 文字列は、webservice から次のようになります。

string json = @"{
""Name"": ""Apple"",
""Beschreibung"": ""Steve Jobs ist tot""}";
4

1 に答える 1

1

この種のネストされたロギングを行う:

NSLog(@"Results %@",[NSString stringWithFormat:@"%@",[[dic objectForKey:@"d"]objectForKey:@"Name"]]);

本当にトリッキーです。「d」が返すオブジェクトは、必ずしもNSDictionaryオブジェクトではなく、おそらくNSArrayであるとは限りません。

次のようなものを試してください。

NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:result options:kNilOptions error:nil];

// this gives the whole NSDictionary output:
NSLog( @"Results %@", [dic description] );

// get the dictionary that corresponds to the key "d"
NSDictionary * dDic = [dic objectForKey: @"d"];
if(dDic)
{
    NSString * nameObject = [dDic objectForKey: @"Name"];
    if(nameObject)
    {
        NSLog( @"object for key 'Name' is %@", nameObject );
    } else {
        NSLog( @"couldn't get object associated with key 'Name'" );
    }
} else {
    NSLog( @"couldn't get object associated with key 'd'") );
}

そして、それがどのレベルでどのオブジェクトであなたの仮定が破られているかを理解するのに役立つかどうかを確認してください。

于 2012-06-05T09:24:39.977 に答える