|
/// <summary>
/// Object扩展类
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// 将一个对象输出为用户友好的Json字符串
/// </summary>
/// <param name="obj">目标对象</param>
/// <param name="resolveCamelCase">是否按照驼峰命名法处理属性名称</param>
/// <returns>用户友好的Json字符串</returns>
public static string ToUserFriendlyJson(this object obj, bool resolveCamelCase = true)
{
return obj.ToJson(resolveCamelCase, Formatting.Indented);
}
/// <summary>
/// 将一个对象输出为Json字符串
/// </summary>
/// <param name="obj">目标对象</param>
/// <param name="resolveCamelCase">是否按照驼峰命名法处理属性名称</param>
/// <param name="formatting">格式设置</param>
/// <returns>表示对象数据的Json字符串</returns>
public static string ToJson(this object obj, bool resolveCamelCase = true, Formatting formatting = Formatting.None)
{
if (obj == null)
throw new ArgumentNullException("obj");
var settings = new JsonSerializerSettings
{
Formatting = formatting,
NullValueHandling = NullValueHandling.Ignore,
};
if (resolveCamelCase)
{
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
return JsonConvert.SerializeObject(obj, settings);
}
}
|
|