//創建一個類,此類有兩個方法
using Newtonsoft.Json;
namespace System
{
public static class JsonExtension
{
/// <summary>
/// 把對象轉換為JSON字符串
/// </summary>
/// <param name="o">對象</param>
/// <returns>JSON字符串</returns>
public static string ToJSON(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 FromJSON<T>(this string input)
{
try
{
return JsonConvert.DeserializeObject<T>(input);
}
catch (Exception ex)
{
return default(T);
}
}
}
}
//使用
User user = new User();
user.UserName = "tom";
user.Age = 22;
user.Sex = 1;
user.Like = "PLAY";
var json= JsonExtension.ToJSON(user);//對象轉為Json
string user = "{\"UserName\":\"tom\",\"Age\":22,\"Sex\":1,\"Like\":\"PLAY\"}";//這裡使用轉義符
var entity = user.FromJSON<User>();//Json轉為實體對象