准备工作:
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[].id);//控制台输入试试
Console.ReadLine();