關於NSJSONSerialization,官方文檔中有如下介紹:You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON. An object that may be converted to JSON must have the following properties: The top level object is an NSArray or NSDictionary.All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.All dictionary keys are instances of NSString.Numbers are not NaN or infinity.我們能利用NSJSONSerialization將JSON轉換成Foundation對象,也能將Foundation對象轉換成JSON,轉換成JSON的對象必須具有如下屬性:頂層對象必須是NSArray或者NSDictionary所有的對象必須是NSString、NSNumber、NSArray、NSDictionary、NSNull的執行個體所有NSDictionary的key必須是NSString類型數字對象不能是非數值或無窮 接下來看看如何使用,首先是如何產生JSON格式的資料:我這裡選用項目中的程式碼片段來進行簡要介紹,以下顯示了登陸請求JSON格式資料的產生[cpp] NSDictionary *registerDic = [NSDictionary dictionaryWithObjectsAndKeys:uuid,@"_id",userName,@"login_name",password,@"password", nil]; if ([NSJSONSerialization isValidJSONObject:registerDic]) { NSError *error; NSData *registerData = [NSJSONSerialization dataWithJSONObject:registerDic options:NSJSONWritingPrettyPrinted error:&error]; NSLog(@"Register JSON:%@",[[NSString alloc] initWithData:registerData encoding:NSUTF8StringEncoding]); } NSDictionary中的key就是json字串中的key,object就是json字串中的value,isValidJSONObject:方法是檢測Foundation對象能否合法轉換為JSON對象,dataWithJSONObject:options:error方法是將Foundation對象轉換為JSON對象,參數NSJSONWritingPrettyPrinted的意思是將產生的json資料格式化輸出,這樣可讀性高,不設定則輸出的json字串就是一整行。 解析服務端返回的json格式資料:[cpp] NSDictionary *resultJSON = [NSJSONSerialization JSONObjectWithData:resultData options:kNilOptions error:&error]; 擷取返回字串中key為status的value:[cpp] NSString *status = [resultJSON objectForKey:@"status"]; 以上就簡要的介紹了下NSJSONSerilazation的使用,不是很全面,以後有時間再深入詳解一下。