首页 > 代码库 > C# JSON字符串序列化与反序列化
C# JSON字符串序列化与反序列化
第一种:使用JavaScriptSerializer类,适用Web平台
C#将对象序列化成JSON字符串
using System.Web.Script; using System.Web.Script.Serialization;
JavaScriptSerializer serializer = new JavaScriptSerializer(); foreach (DataRow dr in dt.Rows) { Dictionary<string, string> data = http://www.mamicode.com/new Dictionary();>
输出结果为:[{"Dev_NO":"00066666","Dev_Name":"test","Ol_Phone":"13766668888","Ol_IP":"10.196.209.174","Ol_Status":"2"},{"Dev_NO":"000F0000","Dev_Name":"test_hzlkhq","Ol_Phone":"13066668888","Ol_IP":"192.168.1.198","Ol_Status":"2"}]如何将Json字符串转换成对象使用呢?
public class Model { public string Dev_NO { get; set; } public string Dev_Name { get; set; } public string Ol_Phone { get; set; } public string Ol_IP { get; set; } public int Ol_Status { get; set; } }
string requestMes="[{\"Dev_NO\":\"00066666\",\"Dev_Name\":\"test\",\"Ol_Phone\":\"13766668888\",\"Ol_IP\":\"10.196.209.174\",\"Ol_Status\":\"2\"},{\"Dev_NO\":\"000F0000\",\"Dev_Name\":\"test_hzlkhq\",\"Ol_Phone\":\"13066668888\",\"Ol_IP\":\"192.168.1.198\",\"Ol_Status\":\"2\"}]"; JavaScriptSerializer serializer = new JavaScriptSerializer(); var Json = serializer.Deserialize<List<Model>>(requestMes);第二种使用DataContractJsonSerializer,适用通用平台需要添加引用:System.ServiceModel.Web 和 System.Runtime.Serialization,然后使用Using:
using System.Runtime.Serialization.Json; using System.Runtime.Serialization;public class Model { public string Dev_NO { get; set; } public string Dev_Name { get; set; } public string Ol_Phone { get; set; } public string Ol_IP { get; set; } public int Ol_Status { get; set; } }public class Test { public static DataTable getData() { var a = "{\"Dev_NO\":\"00066666\",\"Dev_Name\":\"test\",\"Ol_Phone\":\"13766668888\",\"Ol_IP\":\"10.196.209.174\",\"Ol_Status\":\"2\"}"; var serializer = new DataContractJsonSerializer(typeof(List<DTUModel>)); var mStream = new MemoryStream(Encoding.UTF8.GetBytes(a.ToString())); List<DTUModel> list = (List<DTUModel>)serializer.ReadObject(mStream); DataTable dt = new DataTable(); return dt; } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。