2012-04-06 44 views
17

我正在爲登錄應用程序編寫代碼。任何人都可以幫助我如何解析JSON字符串? 我的代碼是如何解析一個json字符串到nsdictionary中?

-(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]; 
+0

您無需使用SBJsonParser只需使用發佈的2行即可解決您的解析問題。 – Kuldeep 2012-04-06 09:51:55

+0

請注意,json.org列出了5個開源JSON解析器,還有iOS/OSx內置的Apple。你可以選擇你想要的任何一個。 – 2013-10-19 20:48:30

回答

45

實施例的數據:

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

//This will give you parsed output. 
+1

在我看來,如果他試圖找到JSONValue是一個未定義的方法。 – 2013-10-19 20:52:10

+1

JSONValue不是NSString的一種方法,它被包含在一個名爲SBJson的包中,我認爲...這個代碼不會開箱即用。更好地使用NSJSONSerialization按照http://stackoverflow.com/questions/10122534/jsonvalue-arc-issue – 2014-05-15 17:42:24

+0

那麼,OP是在他的問題中使用SBJsonParser。 – 2015-06-04 17:18:35

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字符串是:{」 json「:{」Success「:」激活碼。「}}

會話結束後,結果爲-------字典值爲{ Success =「激活碼」};

+2

什麼是JSONValue?一些你在NSString上創建的類別? – 2016-12-19 13:44:08

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]);