19

ログインアプリケーションのコードを書いています。json文字列を解析する方法を教えてもらえますか? 私のコードは

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];

    SBJsonParser *parser = [[SBJsonParser alloc] init];

    NSArray *loginDict = [parser objectWithString:loginDict error:nil];

    [loginStatus release];

    [connection release];
4

4 に答える 4

50

サンプルデータ:

NSString *strData = @"{\"1\": {\"name\": \"Jerry\",\"age\": \"12\"}, \"2\": {\"name\": \"Bob\",\"age\": \"16\"}}";
NSData *webData = [strData dataUsingEncoding:NSUTF8StringEncoding];

NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
NSLog(@"JSON DIct: %@", jsonDict);

NSLog 出力:

JSON DIct: {
     1 =     {
         age = 12;
         name = Jerry;
     };
     2 =     {
         age = 16;
         name = Bob;
     };
}
于 2012-04-06T11:36:54.093 に答える
0
//*************Static Resopnse
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"text"];
NSLog (@"Content: %@", filePath);
NSString *content = [[[NSString alloc] initWithContentsOfFile:filePath
                                                 usedEncoding:nil
                                                        error:nil] autorelease];

SBJSON *json = [[SBJSON new] autorelease];
NSString *str=[[NSString alloc]initWithString:content];
dictTemp = [json objectWithString:str error:nil];
NSLog(@"Actions is: %@",dictTemp);
NSArray *arr=[[dictTemp valueForKey:@"Data"] mutableCopy];
arrX=[[NSMutableArray alloc] init];
arrY=[[NSMutableArray alloc] init];

for(NSDictionary *dict in arr)
{
    [arrX addObject:[dict valueForKey:@"Milestone"]];
    [arrY addObject:[dict valueForKey:@"Sites"]];
}   
NSLog(@"X is: %@",[arrX description]);
NSLog(@"Y is: %@",[arrY description]);
于 2012-11-21T08:57:36.273 に答える
-1
   NSString *responseString = [[NSString alloc] initWithData:responseData encoding:  NSASCIIStringEncoding];
   NSlog(@"json String is: %@",responseString);
   NSDictionary *dictionary = [responseString JSONValue];
   NSLog(@"Dictionary value is  %@", [dictionary objectForKey:@"json"]);

このコードの結果:json 文字列: {"json":{"Success":"Activation code."}}

会話の後、結果は ------- Dictionary の値は { Success = "Activation code."}; です。

于 2012-04-06T14:20:15.103 に答える