///
/// json转换帮助类
///
public static class JsonHelper
{
/*
实例:
JObject obj = new JObject();
obj.Add("code", "0");
obj.Add("msg", "成功");
JArray jarr = new JArray();
JObject now = new JObject();
now.Add("id", 100);
now.Add("name", "关羽");
now.Add("date", "2020-07-21 15:05:21");
jarr.Add(now);
now = new JObject();
now.Add("id", 101);
now.Add("name", "张飞");
now.Add("date", "2020-07-21 15:06:21");
jarr.Add(now);
obj.Add("data", jarr);
TestClass test = JsonHelper.ToObject(obj.ToString());
string json = test.ToJson("yyyy-MM-dd HH:mm:ss");
JObject testClass = JsonHelper.ToJObject(obj.ToString());
public class TestClass
{
public int code { set; get; }
public string msg { set; get; }
public List data { set; get; }
public class dataClass
{
public string id { set; get; }
public string name { set; get; }
public DateTime date { set; get; }
}
}
*/
///
/// 字符串是否为空
///
///
///
public static bool IsNotEmpty(this string value)
{
return string.IsNullOrWhiteSpace(value) == false;
}
///
/// model对象转为json字符串
///
///
///
public static string ToJson(this object obj)
{
return obj == null ? null : JsonConvert.SerializeObject(obj);
}
///
/// model对象转为json字符串
///
///
/// 时间格式,如:yyyy-MM-dd HH:mm:ss yyyy/MM/dd HH:mm:ss
///
public static string ToJson(this object obj, string datetimeformats)
{
var timeConverter = new IsoDateTimeConverter { DateTimeFormat = datetimeformats };
return JsonConvert.SerializeObject(obj, timeConverter);
}
///
/// json字符串转为model对象
///
///
///
///
public static T ToObject(this string Json)
{
try
{
return Json.IsNotEmpty() == false ? default(T) : JsonConvert.DeserializeObject(Json);
}
catch (Exception ex)
{
return default(T);
}
}
///
/// json字符串转为泛型集合
///
///
///
///
public static List ToList(this string Json)
{
return Json == null ? null : JsonConvert.DeserializeObject>(Json);
}
///
/// json字符串转为DataTable表格
///
///
///
public static DataTable ToTable(this string Json)
{
return Json == null ? null : JsonConvert.DeserializeObject(Json);
}
///
/// json字符串转为json对象
///
///
///
public static JObject ToJObject(this string Json)
{
return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace(" ", ""));
}
}