JSON資料的解析

2021-06-28 19:28:33 字數 3564 閱讀 1801

一、什麼是json

json是一種輕量級的資料格式,一般用於資料互動

json的格式很像oc中的字典和陣列

標準json格式的注意點:key必須用雙引號

要想從json中挖掘出具體資料,得對json進行解析。即把json 轉換為 oc資料型別

二、json – oc 轉換對照表

對照關係

三、json解析方案

1.在ios中,json的常見解析方案有4種

(1)第三方框架:jsonkit、sbjson、touchjson(效能從左到右,越差)

(2)蘋果原生(自帶):nsjsonserialization(效能最好)

2.nsjsonserialization的常見方法

(1)json資料 ——》 oc物件

+ (id)jsonobjectwithdata:(nsdata *)data options:(nsjsonreadingoptions)opt error:(nserror **)error;

(2)oc物件 ——》 json資料

+ (nsdata *)datawithjsonobject:(id)obj options:(nsjsonwritingoptions)opt error:(nserror **)error;

3.解析來自伺服器的json示意圖

四、部分**示例

1

#import

"yyviewcontroller.h"2

#import

"mbprogresshud+mj.h"3

4@inte***ce

yyviewcontroller ()

5 @property (weak, nonatomic) iboutlet uitextfield *username;

6 @property (weak, nonatomic) iboutlet uitextfield *pwd;

7 -(ibaction)login;89

@end

1011

@implementation

yyviewcontroller

1213 -(ibaction)login

19if (self.pwd.text.length==0

) 23

//2.傳送請求給伺服器(帶上賬號和密碼)

24//

新增乙個遮罩,禁止使用者操作

25 [mbprogresshud showmessage:@"

正在努力載入中...."];

2627

//28

//1.設定請求路徑

29//

nsstring *urlstr=[nsstring stringwithformat:@"

:8080/mjserver/login?username=%@&pwd=%@",self.username.text,self.pwd.text];

30//

nsurl *url=[nsurl urlwithstring:urlstr];

3132

//1.設定請求路徑

33 nsurl *url=[nsurl urlwithstring:@"

:8080/mjserver/login

"];//

不需要傳遞引數

3435

//2.建立請求物件

36 nsmutableurlrequest *request=[nsmutableurlrequest requestwithurl:url];//

預設為get請求

37 request.timeoutinterval=5.0;//

設定請求超時為5秒

設定請求方法

3940

//設定請求體

41 nsstring *param=[nsstring stringwithformat:@"

username=%@&pwd=%@

",self.username.text,self.pwd.text];

42//

把拼接後的字串轉換為data,設定請求體

//客戶端型別,只能寫英文

//3.傳送請求

49//

獲取乙個主佇列

50 nsoperationqueue *queue=[nsoperationqueue mainqueue];

51 [nsurlconnection sendasynchronousrequest:request queue:queue completionhandler:^(nsurlresponse *response, nsdata *data, nserror *connectionerror) else

6165 }else

//請求失敗

6669

}];70 nslog(@"

請求傳送完畢");

71}72@end

JSON資料的解析

在解析json資料時,往往遇到的json格式並沒有書上列舉的那麼簡單,在此我舉例幾種json格式 這下面json資料來自於一篇別人的部落格 private void parsejsonwithjsonobject string jsondata catch exception e private v...

json資料解析

由於是從網路上面讀取json,因此需要讀取網路檔案 url url new url path httpurlconnection conn httpurlconnection url.openconnection 利用httpurlconnection物件,我們可以從網路中獲取網頁資料.conn.s...

json資料解析

今天在做easyui列表頁面回顯字典表資料時候遇到乙個json解析的奇怪問題,首先我用spring gethibernatetemplate 中的createsqlquery進行資料查詢 查出來的資料是 2,2,2,2,2,2,2,之類的 public list findbypage final s...