C#中json格式數據反序列化為Dictionary


需求:從web.config中讀取配置節點,經過C#代碼處理后顯示在前台頁面上去,如下圖所示:

目的是實現英文縮寫加上他的中文描述。

解決方案:

1.存入數據庫,存數據庫讀取然后拼湊字符串(不做討論)

2.從web.config中讀取,存入時存入兩行,讀兩次,然后對應拼湊字符串然后綁定。(不做討論)

3.從web.config中讀取,直接在web.config中存入json格式的數據,讀取后經過反序列化后存入Dictionary<string,string>里面,然后進行遍歷拼湊。

 

web.config存放樣例:

 

C# 反序列化代碼:在一個單獨的類庫里里面

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Web;
 6 using System.Runtime.Serialization;
 7 using System.Configuration;
 8 using System.Runtime.Serialization.Json;
 9 using System.IO;
10 
11 namespace Lib
12 {
13     public class jsonHelper
14     {
15         public static Dictionary<string, string> getJson(string jsonString)
16         {
17             DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Dictionary<string, string>));
18             MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
19             Dictionary<string, string> jsonObject = (Dictionary<string, string>)ser.ReadObject(ms);
20             return jsonObject;
21         }
22     }
23 }

調用代碼:Default.aspx頁面

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Configuration;
 7 using System.Web.UI.WebControls;
 8 
 9 using Lib;
10 
11 public partial class _Default : System.Web.UI.Page
12 {
13     protected void Page_Load(object sender, EventArgs e)
14     {
15         //從web.config獲取json格式數據
16         string jsonText = ConfigurationManager.AppSettings["IOType"].ToString();
17 
18         Dictionary<string, string> json = json = jsonHelper.getJson(jsonText);
19 
20         //遍歷拼湊綁定
21         foreach (KeyValuePair<string, string> Kvalue in json)
22         {
23             ddlIOType.Items.Add(new ListItem(Kvalue.Key + " (" + Kvalue.Value+")",Kvalue.Key));
24         }
25     }
26 }

 

顯示效果:

注意的地方:

在定義web.config里面的Json的數據時要特別在意,要想反序列化為字典存儲,就必須加上Key和Value少了Key和Value不能反序列化成功。

另外需要注意的一點就是json數據的格式,尤其是引號,如果你在程序中定義json格式數據的時候需要在引號前加上轉義符才行,如下面的格式:

1 string strJsonText="[{\"Key\":\"USD\",\"Value\":\"美元\"},{\"Key\":\"GBP\",\"Value\":\"英鎊\"},{\"Key\":\"EUR\",\"Value\":\"歐元\"}]";

過如向web.config中那樣定義,轉義符不用自己加,編譯器在做轉化時幫我們自己添加了。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM