/// <summary> /// 将 JSON 转为对象 /// </summary> /// <typeparam name="T">将要序列化的对象作为泛型参数</typeparam> /// <param name="jsonStr">JSON 字符串</param> /// <param name="type">要序列化的对象 Type</param> /// <returns>返回对象</returns> public static T JsonToObject<T>(string jsonStr, Type type) {//引用自:using System.Runtime.Serialization.Json; 类库没有
//实例化类 (要序列化的类型) DataContractJsonSerializer json = new DataContractJsonSerializer(type); using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr.Replace(" ", @"")))) { try { T tt = (T)json.ReadObject(stream); return tt; } catch { throw new Exception("反序列化失败,请检查所提供的序列化内容和类型..."); } } }
/// <summary> /// json转集合 /// </summary> /// <typeparam name="T">泛型对象</typeparam> /// <param name="json">json字符串</param> /// <param name="t">转化类型</param> /// <returns>集合</returns> public static List<T> Json2Obj<T>(string json, Type t) { List<T> list = new List<T>(); try { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(t); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { T tt =(T)serializer.ReadObject(ms); list.Add(tt); return list; } } catch { return null; } }
//对象转集合 引入 Newtonsoft.Json ReturnData rd = JsonConvert.DeserializeObject<ReturnData>(jason,type);
/// <summary> /// 对象转换为Json /// </summary> /// <param name="en"></param> /// <returns></returns> public string GetJsonObj(UserLogins use) { System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(use.GetType()); System.IO.MemoryStream stra = new System.IO.MemoryStream(); ser.WriteObject(stra, use); byte[] bute = new byte[stra.Length]; stra.Position = 0; stra.Read(bute, 0, (int)stra.Length); string BodyJson = Encoding.UTF8.GetString(bute); return BodyJson ; }
/// <summary> /// 对象转为Json数组 /// </summary> /// <param name="dic"></param> /// <returns></returns> private string GetToJson(object dic) { //实例化JavaScriptSerializer类的新实例 System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); try { //将对象序列化为json数据 string json = jss.Serialize(dic); return json; } catch (Exception ex) { throw new Exception(ex.Message); } }