C# JavaScriptSerializer 解析Json數據(多方法解析Json 三)


准備工作:

1、添加引用System.Web.Extensions,

2、.net3.5+版本都有,如果VS2010找不到,在這個文件夾找:C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\

3、再using System.Web.Script.Serialization;即可

 

實現:

方法一

       var js = new System.Web.Script.Serialization.JavaScriptSerializer();
            string json = "{\"offlineLock\":[{\"id\":\"4028d808581dab0f01581db51405001e\",\"mac\":\"D4:3D:7E:5F:B7:44\",\"sdsl\":5,\"sdrq\":1477967156304,\"shlb\":\"0\"}],\"flag\":\"success\",\"status\":\"1400\",\"resultList\":[{\"id\":\"4028d808581dab0f01581db5145c001f\",\"zwjyzsbh\":\"1000001600000052\",\"sfyfz\":\"0\"},{\"id\":\"4028d808581dab0f01581db514780020\",\"zwjyzsbh\":\"1000001600000054\",\"sfyfz\":\"0\"},{\"id\":\"4028d808581dab0f01581db514950021\",\"zwjyzsbh\":\"1000001600000056\",\"sfyfz\":\"0\"},{\"id\":\"4028d808581dab0f01581db514b20022\",\"zwjyzsbh\":\"1000001600000058\",\"sfyfz\":\"0\"},{\"id\":\"4028d808581dab0f01581db514cc0023\",\"zwjyzsbh\":\"1000001600000060\",\"sfyfz\":\"0\"}]}";
            var jarr = js.Deserialize<Dictionary<string, object>>(json);
            foreach(var j in jarr)
            {
                Console.WriteLine(string.Format("{0}:{1}", j.Key, j.Value));
            }
            Console.ReadLine();

 

方法二:

1、建好實體類,對應json數據里的key

class Lock
    {
        public List<OfflineLock> offlineLock { get; set; }
        public string flag { get; set; }
        public string status { get; set; }
        public List<ResultList> resultList { get; set; } }
class OfflineLock
    {
        public string id { get; set; }
        public string mac { get; set; }
        public long sdsl { get; set; }
        public long sdrq { get; set; }
        public string shlb { get; set; }
    }
class ResultList
{ 

public string id { get; set; }

public string sfyfz { get; set; }

public string zwjyzsbh { get; set; }
}

 

2、JavaScriptSerializer 解析Json數據

string json = "{\"offlineLock\":[{\"id\":\"4028d808581dab0f01581db51405001e\",\"mac\":\"D4:3D:7E:5F:B7:44\",\"sdsl\":5,\"sdrq\":1477967156304,\"shlb\":\"0\"}],\"flag\":\"success\",\"status\":\"1400\",\"resultList\":[{\"id\":\"4028d808581dab0f01581db5145c001f\",\"zwjyzsbh\":\"1000001600000052\",\"sfyfz\":\"0\"},{\"id\":\"4028d808581dab0f01581db514780020\",\"zwjyzsbh\":\"1000001600000054\",\"sfyfz\":\"0\"},{\"id\":\"4028d808581dab0f01581db514950021\",\"zwjyzsbh\":\"1000001600000056\",\"sfyfz\":\"0\"},{\"id\":\"4028d808581dab0f01581db514b20022\",\"zwjyzsbh\":\"1000001600000058\",\"sfyfz\":\"0\"},{\"id\":\"4028d808581dab0f01581db514cc0023\",\"zwjyzsbh\":\"1000001600000060\",\"sfyfz\":\"0\"}]}";

            JavaScriptSerializer  js = new JavaScriptSerializer();
            Lock str=js.Deserialize<Lock>(json);

            Console.WriteLine(str.offlineLock[0].id);//控制台輸入試試
            Console.ReadLine();

 


免責聲明!

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



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