namespace Demo
{
public static class Extends
{
// string类型扩展ToJson方法
public static object ToJson(this string Json)
{
return Json == null ? null : JsonConvert.DeserializeObject(Json);
}
// object类型扩展ToJson方法
public static string ToJson(this object obj)
{
var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
return JsonConvert.SerializeObject(obj, timeConverter);
}
public static string ToJson(this object obj, string datetimeformats)
{
var timeConverter = new IsoDateTimeConverter { DateTimeFormat = datetimeformats };
return JsonConvert.SerializeObject(obj, timeConverter);
}
public static T ToObject<T>(this string Json)
{
return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json);
}
public static List<T> ToList<T>(this string Json)
{
return Json == null ? null : JsonConvert.DeserializeObject<List<T>>(Json);
}
public static DataTable ToTable(this string Json)
{
return Json == null ? null : JsonConvert.DeserializeObject<DataTable>(Json);
}
public static JObject ToJObject(this string Json)
{
return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace(" ", ""));
}
} class Program
{
static void Main(string[] args)
{
try
{
List<User> users = new List<User>{
new User{ID="1",Code="zs",Name="张三"},
new User{ID="2",Code="ls",Name="李四"}
}; // list转化json字符串
string json = users.ToJson();
// string转化List
users = json.ToList<User>(); // string转化DataTable
DataTable dt = json.ToTable();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
Console.ReadLine();
}
}
} public class User
{
public string ID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
}