一文掌握c#json(2023最新整理)
最近在做微信開發時用到了一些json的問題,就是把微信返回回來的一些json數據做一些處理,但是之前json掌握的不好,浪費了好多時間在查找一些json有關的轉換問題,我所知道的方法只有把json序列化和反序列化一下,但是太麻煩了我覺得,所以就在找一些更簡單又方便使用的方法。也許這個會有用吧,所以先放到這以后能用到的。
json的全稱是”javascript object notation”,意思是javascript對象表示法,它是一種基于文本,獨立于語言的輕量級數據交換格式。xml也是一種數據交換格式,為什么沒 有選擇xml呢?因為xml雖然可以作為跨平臺的數據交換格式,但是在js(javascript的簡寫)中處理xml非常不方便,同時xml標記比數據 多,增加了交換產生的流量,而json沒有附加的任何標記,在js中可作為對象處理,所以我們更傾向于選擇json來交換數據。這篇文章主要從以下幾個方 面來說明json。
1,json的兩種結構
2,認識json字符串
3,在js中如何使用json
4,在.net中如何使用json
5,總結
json的兩種結構
json有兩種表示結構,對象和數組。
對象結構以”{”大括號開始,以”}”大括號結束。中間部分由0或多個以”,”分隔的”key(關鍵字)/value(值)”對構成,關鍵字和值之間以”:”分隔,語法結構如代碼。
{ key1:value1, key2:value2, ... }
其中關鍵字是字符串,而值可以是字符串,數值,true,false,null,對象或數組
數組結構以”[”開始,”]”結束。中間由0或多個以”,”分隔的值列表組成,語法結構如代碼。
[ { key1:value1, key2:value2 }, { key3:value3, key4:value4 } ]
認識json字符串
之前我一直有個困惑,分不清普通字符串,json字符串和json對象的區別。經過一番研究終于給弄明白了。比如在js中。
字符串:這個很好解釋,指使用“”雙引號或’’單引號包括的字符。例如:var comstr = 'this is string';
json字符串:指的是符合json格式要求的js字符串。例如:var jsonstr = "{studentid:'100',name:'tmac',hometown:'usa'}";
json對象:指符合json格式要求的js對象。例如:var jsonobj = { studentid: "100", name: "tmac", hometown: "usa" };
在js中如何使用json
json是js的一個子集,所以可以在js中輕松地讀,寫json。讀和寫json都有兩種方法,分別是利用”.”操作符和“[key]”的方式。
我們首先定義一個json對象,代碼如下。
var obj = { "1": "value1", "2": "value2", count: 3, person: [ //數組結構json對象,可以嵌套使用 { id: 1, name: "張倩" }, { id: 2, name: "張帥" } ], object: { //對象結構json對象 id: 1, msg: "對象里的對象" } };
1,從json中讀數據
function readjson() { alert(obj.1); //會報語法錯誤,可以用alert(obj["1"]);說明數字最好不要做關鍵字 alert(obj.2); //同上 alert(obj.person[0].name); //或者alert(obj.person[0]["name"]) alert(obj.object.msg); //或者alert(obj.object["msg"]) }
2,向json中寫數據
比如要往json中增加一條數據,代碼如下:
function add() { //往json對象中增加了一條記錄 obj.sex= "男" //或者obj["sex"]="男" }
增加數據后的json對象如圖:
3,修改json中的數據
我們現在要修改json中count的值,代碼如下:
function update() { obj.count = 10; //或obj["count"]=10 }
修改后的json如圖。
4,刪除json中的數據
我們現在實現從json中刪除count這條數據,代碼如下:
function delete() { delete obj.count; }
刪除后的json如圖
可以看到count已經從json對象中被刪除了。
5,遍歷json對象
可以使用for…in…循環來遍歷json對象中的數據,比如我們要遍歷輸出obj對象的值,代碼如下:
function traversal() { for (var c in obj) { console.log(c + ":", obj[c]); } }
程序輸出結果為:
在.net中如何使用json
說到在.net中使用json,就不得不提到json.net,它是一個非常著名的在.net中處理json的工具,我們最常用的是下面兩個功能。
1,通過序列化將.net對象轉換為json字符串
在web開發過程中,我們經常需要將從數據庫中查詢到的數據(一般為一個集合,列表或數組等)轉換為json格式字符串傳回客戶端,這就需要進行序 列化,這里用到的是jsonconvert對象的serializeobject方法。其語法格式 為:jsonconvert.serializeobject(object),代碼中的”object”就是要序列化的.net對象,序列化后返回的是 json字符串。
比如,現在我們有一個tstudent的學生表,表中的字段和已有數據如圖所示
從表中我們可以看到一共有五條數據,現在我們要從數據庫中取出這些數據,然后利用json.net的jsonconvert對象序列化它們為json字符串,并顯示在頁面上。c#代碼如下
protected void page_load(object sender, eventargs e) { using (l2sdbdatacontext db = new l2sdbdatacontext()) { list<student> studentlist = new list<student>(); var query = from s in db.tstudents select new { studentid=s.studentid, name=s.name, hometown=s.hometown, gender=s.gender, brithday=s.birthday, classid=s.classid, weight=s.weight, height=s.height, desc=s.desc }; foreach (var item in query) //循環遍歷數組,轉換對象 { student student = new student { studentid=item.studentid,name=item.name,hometown=item.hometown,gender=item.gender,brithday=item.brithday,classid=item.classid,weight=item.weight,height=item.height,desc=item.desc}; studentlist.add(student); } lbmsg.innertext = jsonconvert.serializeobject(studentlist); } }
輸出結果
從圖中我們可以看到,數據庫中的5條記錄全部取出來并轉化為json字符串了。
2,使用linq to json定制json數據
使用jsonconvert對象的serializeobject只是簡單地將一個list或集合轉換為json字符串。但是,有的時候我們的前端 框架比如extjs對服務端返回的數據格式是有一定要求的,比如下面的數據格式,這時就需要用到json.net的linq to json,linq to json的作用就是根據需要的格式來定制json數據。
比如經常用在分頁的json格式如代碼:
{ "total": 5, //記錄總數 "rows":[ //json格式的數據列表 ] }
使用linq to json前,需要引用newtonsoft.json的dll和using newtonsoft.json.linq的命名空間。linq to json主要使用到jobject, jarray, jproperty和jvalue這四個對象,jobject用來生成一個json對象,簡單來說就是生成”{}”,jarray用來生成一個json數 組,也就是”[]”,jproperty用來生成一個json數據,格式為key/value的值,而jvalue則直接生成一個json值。下面我們就 用linq to json返回上面分頁格式的數據。代碼如下:
protected void page_load(object sender, eventargs e) { using (l2sdbdatacontext db = new l2sdbdatacontext()) { //從數據庫中取出數據并放到列表list中 list<student> studentlist = new list<student>(); var query = from s in db.tstudents select new { studentid = s.studentid, name = s.name, hometown = s.hometown, gender = s.gender, brithday = s.birthday, classid = s.classid, weight = s.weight, height = s.height, desc = s.desc }; foreach (var item in query) { student student = new student { studentid = item.studentid, name = item.name, hometown = item.hometown, gender = item.gender, brithday = item.brithday, classid = item.classid, weight = item.weight, height = item.height, desc = item.desc }; studentlist.add(student); } //基于創建的list使用linq to json創建期望格式的json數據 lbmsg.innertext = new jobject( new jproperty("total",studentlist.count), new jproperty("rows", new jarray( //使用linq to json可直接在select語句中生成json數據對象,無須其它轉換過程 from p in studentlist select new jobject( new jproperty("studentid",p.studentid), new jproperty("name",p.name), new jproperty("hometown",p.hometown) ) ) ) ).tostring(); } }
輸出結果為:
3,處理客戶端提交的json數據
客戶端提交過來的數據一般都是json字符串,有了更好地進行操作(面向對象的方式),所以我們一般都會想辦法將json字符串轉換為json對象。例如客戶端提交了以下數組格式json字符串。
[ {studentid:"100",name:"aaa",hometown:"china"}, {studentid:"101",name:"bbb",hometown:"us"}, {studentid:"102",name:"ccc",hometown:"england"} ]
在服務端就可以使用jobject或jarray的parse方法輕松地將json字符串轉換為json對象,然后通過對象的方式提取數據。下面是服務端代碼。
protected void page_load(object sender, eventargs e) { string inputjsonstring = @" [ {studentid:'100',name:'aaa',hometown:'china'}, {studentid:'101',name:'bbb',hometown:'us'}, {studentid:'102',name:'ccc',hometown:'england'} ]"; jarray jsonobj = jarray.parse(inputjsonstring); string message = @"<table border='1'> <tr><td width='80'>studentid</td><td width='100'>name</td><td width='100'>hometown</td></tr>"; string tpl = "<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>"; foreach (jobject jobject in jsonobj) { message += string.format(tpl, jobject["studentid"], jobject["name"],jobject["hometown"]); } message += "</table>"; lbmsg.innerhtml = message; }
輸出結果:
當然,服務端除了使用linq to json來轉換json字符串外,也可以使用jsonconvert的deserializeobject方法。如下面代碼實現上面同樣的功能。
list<student> studentlist = jsonconvert.deserializeobject<list<student>>(inputjsonstring);//注意這里必須為list<student>類型,因為客戶端提交的是一個數組json foreach (student student in studentlist) { message += string.format(tpl, student.studentid, student.name,student.hometown); }
總結
在客戶端,讀寫json對象可以使用”.”操作符或”["key”]”,json字符串轉換為json對象使用eval()函數。
在服務端,由.net對象轉換json字符串優先使用jsonconvert對象的serializeobject方法,定制輸出json字符串使用linq to json。由json字符串轉換為.net對象優先使用jsonconvert對象的deserializeobject方法,然后也可以使用linq to json。
根據所需調用方法就行。不過也可以用newtonsoft.json這個dll文件,如果轉換數組的話就用
jobject json = (jobject)jsonconvert.deserializeobject(str); jarray array = (jarray)json["article"]; foreach (var jobject in array) { //賦值屬性 }
關于一文掌握c# json(2023最新整理)的文章就介紹至此,更多相關c# json內容請搜索碩編程以前的文章,希望以后支持碩編程!