#region 将JSON格式字符转换成对象 /// <summary> /// 将JSON格式字符转换成对象 /// </summary> /// <typeparam name="T">需要转换的对象类型</typeparam> /// <param name="target">JSON目标</param> /// <returns>转换结果</returns> public static T JsonDeserialize<T>(this string target) { try { using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(target))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); return (T)serializer.ReadObject(ms); } } catch (Exception ex) { return default(T); } } #endregion #region 将对象转换为JSON格式的字符串 /// <summary> /// 将对象转换为JSON格式的字符串 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="target">对象目标</param> /// <returns>转换结果</returns> public static string JsonSerialize<T>(this T target) { try { T result = (T)target; DataContractJsonSerializer json = new DataContractJsonSerializer(result.GetType()); using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, result); return Encoding.UTF8.GetString(stream.ToArray()); } } catch (Exception ex) { return null; } } #endregion
我的调用:但是mes对象为空,不知道是不是用错了
SysMessage mes= JsonHelper.JsonDeserialize<SysMessage>(JsonString);
[Serializable] public partial class SysMessage { public string returnData { get; set; } }
调试的时候报错:
数据协定类型“Yuyue.WPF.login+SysMessage”无法反序列化,因为未找到必需的数据成员“<returnData>k__BackingField”。
[Serializable]
public class SysMessage
{
public string returnData = string.Empty;
}
去除实体类中的属性就可以了