1.实体转Json
需要添加引用:System.ServiceModel.Web 和 System.Runtime.Serialization,然后使用Using:
/// <summary> /// 获取将实体类转换为json数据(目的是为了更快在网页上传递数据) /// </summary> /// <returns></returns> public string GetJsonInfo(DatasModel dm) { //将对象序列化json DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DatasModel)); //创建存储区为内存流 System.IO.MemoryStream ms = new MemoryStream(); //将json字符串写入内存流中 serializer.WriteObject(ms, dm); System.IO.StreamReader reader = new StreamReader(ms); ms.Position = 0; string strRes = reader.ReadToEnd(); reader.Close(); ms.Close(); return strRes; }
2.json转实体
(ExtractModel为测试实体)
public static ExtractModel DeserializeJsonToObjectss<ExtractModel>(string json) where ExtractModel : class { try { JsonSerializer serializer = new JsonSerializer(); StringReader sr = new StringReader(json); object o = serializer.Deserialize(new JsonTextReader(sr), typeof(ExtractModel)); ExtractModel t = o as ExtractModel; return t; } catch (Exception ex) { return null; }