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 *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]
NSLog([[loginStatus JSONValue] description],nil);

//This will give you parsed output.
于 2012-04-06T09:44:55.840 回答
-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 String is: {"json":{"Success":"Activation code."}}

对话后的结果是------- 字典值为 { Success = "Activation code."};

于 2012-04-06T14:20:15.103 回答