2011-11-04 103 views
0

Possible Duplicate:
How to parse JSON in iOS AppIPhone解析JSON

我有以下的JSON:

NSString *jsonResult = @"{\"code\":\"000\",\"message\":\"success\",\"datas\":[{\"datas\":[{\"service_name\":\"user_info\",\"name\":\"Account Test 32\",\"number\":123,\"company\":\"ABC\",\"currency\":\"USD\",\"balance\":\"1000\",\"profit\":\"-80.00\",\"credit\":\"0.00\",\"equity\":\"1000.00\",\"leverage\":100,\"free_margin\":\"1000.00\",\"free_margin_mode\":1.0,\"server_name\":\"localhost\",\"stopout_level\":5,\"stopout_mode\":0}],\"service_name\":\"user_info\"}]}"; 

誰能舉個例子如何解析呢?

+0

你爲什麼要解析JSON?這是你從web服務獲得的有效載荷嗎? – rjgonzo

+0

是的,它是來自Web服務的有效載荷。 – user772315

回答

1

您最好的選擇是使用JSON解析庫,如TouchJson

2

試試這個。進口SBJson parser你也可以使用TouchJson,但我更喜歡SBJson。

#import "JSON.h" 

// Create SBJSON object to parse JSON 
SBJSON *parser = [[SBJSON alloc] init]; 

// parse the JSON string into an object - assuming json_string is a NSString of JSON data 
NSDictionary *object = [parser objectWithString:jsonResult error:nil]; 
+0

我如何獲得數據數組內的值? – user772315

+0

你有'jsonResult'嗎?將其傳遞給JSON解析器。它會轉換爲ObjectiveC對象...這就是你需要的對嗎?所以我寫的是解析器部分。你在哪裏導入json解析器&解析字符串.... –

+0

它仍然給我一個錯誤:SBJsonParser * json = [[SBJsonParser alloc] init]; NSError * jsonError; NSDictionary * parsedJSON = [json objectWithString:jsonResult error:&jsonError]; NSDictionary * jsonValue = [parsedJSON objectForKey:@「code」]; NSLog(@「code:%@」,[jsonValue objectForKey:@「code」]); – user772315