json extionsion
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Discovery.Utilities.Format
{
public static class StringExtension
{
public static string ToJson(this object obj)
{
if (obj == null)
{
return "";
}
return JsonConvert.SerializeObject(obj, Formatting.Indented, new CustomDateTimeConverter());
}
public static string ToJsonNoIndented(this object obj)
{
if (obj == null)
{
return "";
}
return JsonConvert.SerializeObject(obj, Formatting.None, new CustomDateTimeConverter());
}
/// <summary></summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJsonNoIndentedNoNull(this object obj)
{
if (obj == null)
{
return "";
}
var jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Converters = new List<JsonConverter>() { new CustomDateTimeConverter() } };
return JsonConvert.SerializeObject(obj, Formatting.None, jSetting);
}
public static object DeserializeObject(this string value)
{
return JsonConvert.DeserializeObject(value);
}
/// <summary>
/// if null return "", if less than count return source string, if longer than count cut to count.
/// </summary>
/// <param name="str"></param>
/// <param name="length">length</param>
/// <returns></returns>
public static string LimitTo(this string str, int length)
{
if (string.IsNullOrEmpty(str))
{
return str;
}
if (str.Length > length)
{
return str.Substring(0, length);
}
return str;
}
}
public class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
base.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
}
}
}
posted on 2016-07-26 17:18 Henry_Wang 阅读(323) 评论(0) 编辑 收藏 举报