如何将json字符串解析为nsdictionary?

时间:2012-04-06 09:37:46

标签: iphone objective-c

我正在编写登录应用程序的代码。任何人都可以帮我解析如何解析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 个答案:

答案 0 :(得分:46)

示例数据:

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

答案 1 :(得分:0)

NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]
NSLog([[loginStatus JSONValue] description],nil);

//This will give you parsed output.

答案 2 :(得分:0)

   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 String is:{“json”:{“Success”:“激活码。”}}

对话结果后-------字典值为{     Success =“激活码。”};

答案 3 :(得分: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]);