Json 和对象的相互转换
/// <summary>
/// Json 和对象的相互转换 ——需引用using Newtonsoft.Json; 即:Jsonnet.net.....
/// </summary>
public static class JsonHelper
{
/// <summary>
/// 把对象转换为JSON字符串
/// </summary>
/// <param name="o">对象</param>
/// <returns>JSON字符串</returns>
public static string ObjectToJson(this object o)
{
if (o == null) return null;
return JsonConvert.SerializeObject(o);
}
/// <summary>
/// 把Json文本转为实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="input"></param>
/// <returns></returns>
public static T JsonToObject<T>(this string input)
{
try
{
return JsonConvert.DeserializeObject<T>(input);
}
catch (Exception ex)
{
return default(T);
}
}
}
使用如下所示:
private void btnObjToJson_Click(object sender, EventArgs e)
{
List<Test> timePart = new List<Test>();
timePart.Add(new Test { BeginTime = 8.10, EndTime = 8.15 });
timePart.Add(new Test { BeginTime = 8.15, EndTime = 8.25 });
timePart.Add(new Test { BeginTime = 8.26, EndTime = 8.55 });
string json = JsonHelper.ObjectToJson(timePart);
MessageBox.Show("json\r\n==" + json);
}
private void btnJsonToObj_Click(object sender, EventArgs e)
{
List<Test> timePart = new List<Test>();
timePart.Add(new Test { BeginTime = 8.10, EndTime = 8.15 });
timePart.Add(new Test { BeginTime = 8.15, EndTime = 8.25 });
timePart.Add(new Test { BeginTime = 8.26, EndTime = 8.55 });
string json = JsonHelper.ObjectToJson(timePart);
List<Test> list = JsonHelper.JsonToObject<List<Test>>(json);
MessageBox.Show("list==" +list.Count);
}