public static string SerializeObject(object obj, int maxDepth) { /* * var settings = new Newtonsoft.Json.JsonSerializerSettings() * { * ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, * MaxDepth = 1, * * Error = (sender, errorArgs) => { * var currentError = errorArgs.ErrorContext.Error.Message; * errorArgs.ErrorContext.Handled = true; * } * }; */ using (var strWriter = new StringWriter()) { using (var jsonWriter = new CustomJsonTextWriter(strWriter)) { Func <bool> include = () => jsonWriter.CurrentDepth <= maxDepth; var resolver = new CustomContractResolver(include); var serializer = new JsonSerializer() { ContractResolver = resolver, Formatting = Formatting.Indented, ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; serializer.Serialize(jsonWriter, obj); } return(strWriter.ToString()); } }
/// <inheritdoc /> public override byte[] Serialize(object value) { using (var stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture)) using (var writer = new CustomJsonTextWriter(stringWriter)) { writer.Formatting = _serializer.Formatting; _serializer.Serialize(writer, value, typeof(object)); return(Encoding.UTF8.GetBytes(stringWriter.ToString())); } }
public static string SerializeWithCustomIndenting(object obj) { using (StringWriter sw = new StringWriter()) using (JsonWriter jw = new CustomJsonTextWriter(sw)) { jw.Formatting = Formatting.Indented; JsonSerializer ser = new JsonSerializer(); ser.Serialize(jw, obj); return(sw.ToString()); } }
private string SerializeObject(object obj, int maxDepth) { using (var strWriter = new StringWriter()) { using (var jsonWriter = new CustomJsonTextWriter(strWriter)) { var resolver = new CustomContractResolver(() => jsonWriter.CurrentDepth <= maxDepth); var serializer = new JsonSerializer { ContractResolver = resolver, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented }; serializer.Serialize(jsonWriter, obj); } return(strWriter.ToString()); } }
public static string SerializeObject(object obj, int maxDepth) { using (var strWriter = new StringWriter()) { using (var jsonWriter = new CustomJsonTextWriter(strWriter)) { Func <bool> include = () => jsonWriter.CurrentDepth <= maxDepth; var resolver = new CustomContractResolver(include); var serializer = new JsonSerializer { ContractResolver = resolver }; serializer.Serialize(jsonWriter, obj); } return(strWriter.ToString()); } }