using Newtonsoft.Json;
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace AccpStudentMIS{ //此类目的是防治序列化Json字符串时的循环引用问题 //此类为Object类的扩展方法,需要引用Newtonsoft.Json.dll类 //使用方法:在Controller中调用 Content(对象.ToJsonString(), "text/html;charset=UTF-8");方法来返回Json public static class ObjectExtentions { public static string ToJsonString(this Object obj) { JsonSerializerSettings jsSettings = new JsonSerializerSettings(); jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; return JsonConvert.SerializeObject(obj, jsSettings); } }}
记录Newtonsoft在序列成Json时的两个妙用
JsonSerializerSettings js = new JsonSerializerSettings();
//1、属性为Null时不做序列化输出
js.NullValueHandling = NullValueHandling.Ignore;
//2、属性为DateTime时,做指定的格式输出
js.Converters.Add(new IsoDateTimeConverter()
{ DateTimeFormat ="yyyy-MM-dd HH:mm:ss" });
JsonConvert.SerializeObject(obj, Formatting.None, js);
//3、设定某个属性不做json序列化输出(在属性头加[JsonIgnore])
[JsonIgnore]
public string Srl { get; set; }
/// <summary>
/// 转化为JSON格式 /// </summary> /// <param name="obj"></param> /// <param name="depth">RecursionLimit</param> /// <returns></returns> public static string ToJson(this object obj, int maxDepth = 10) { JsonSerializerSettings settings = new JsonSerializerSettings(); //settings.MaxDepth = maxDepth; settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; settings.Converters.Add(new JavaScriptDateTimeConverter()); return JsonConvert.SerializeObject(obj, settings); }public static string ToJsonIsoDateTime(this object obj)
{ JsonSerializerSettings settings = new JsonSerializerSettings(); settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; settings.Converters.Add(new IsoDateTimeConverter()); return JsonConvert.SerializeObject(obj, settings); }/// <summary>
/// 将JSON反序列化为对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sJason"></param> /// <returns></returns> public static T FromJson<T>(this string obj, int maxDepth = 2) { JsonSerializerSettings settings = new JsonSerializerSettings(); //settings.MaxDepth = maxDepth; settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; settings.Converters.Add(new JavaScriptDateTimeConverter()); return JsonConvert.DeserializeObject<T>(obj, settings); }/// <summary>
/// 将JSON反序列化为对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sJason"></param> /// <returns></returns> public static T FromJsonIsoDateTime<T>(this string obj) { return JsonConvert.DeserializeObject<T>(obj, new IsoDateTimeConverter()); }
/// <summary>
/// 转化为JSON格式 /// </summary> /// <param name="obj"></param> /// <param name="depth">RecursionLimit</param> /// <returns></returns> public static string ToJson(object obj, int maxDepth = 2) { return obj.ToJson(maxDepth); }/// <summary>
/// 将JSON反序列化为对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sJason"></param> /// <returns></returns> public static T FromJson<T>(string obj, int maxDepth = 2) { return obj.FromJson<T>(maxDepth); }