json序列化及反序列化

         /// <summary>
/// 把对象序列化 JSON 字符串
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="obj">对象实体</param>
/// <returns>JSON字符串</returns>
public static string GetJson<T>(T obj)
{
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
json.WriteObject(ms, obj);
string resultJson= Encoding.UTF8.GetString(ms.ToArray());
return resultJson;
}
}
/// <summary>
/// 把JSON字符串还原为对象
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="resultJson">JSON字符串</param>
/// <returns>对象实体</returns>
public static T ParseFormJson<T>(string resultJson)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resultJson)))
{
DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
return (T)dcj.ReadObject(ms);
}
}

  

上一篇:iOS开发之--为UITextField监听数值变化的三种方法


下一篇:ORacle修改表列长度