这在Json.NETJsonWriter
中使用和序列化程序之间的一些协调是可能的ContractResolver
。
自定义JsonWriter
在对象启动时递增计数器,然后在结束时再次递减。
public class CustomJsonTextWriter : JsonTextWriter
{
public CustomJsonTextWriter(TextWriter textWriter) : base(textWriter) {}
public int CurrentDepth { get; private set; }
public override void WriteStartObject()
{
CurrentDepth++;
base.WriteStartObject();
}
public override void WriteEndObject()
{
CurrentDepth--;
base.WriteEndObject();
}
}
自定义对将用于验证当前深度的所有属性ContractResolver
应用特殊谓词。ShouldSerialize
public class CustomContractResolver : DefaultContractResolver
{
private readonly Func<bool> _includeProperty;
public CustomContractResolver(Func<bool> includeProperty)
{
_includeProperty = includeProperty;
}
protected override JsonProperty CreateProperty(
MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
var shouldSerialize = property.ShouldSerialize;
property.ShouldSerialize = obj => _includeProperty() &&
(shouldSerialize == null ||
shouldSerialize(obj));
return property;
}
}
以下方法显示了这两个自定义类如何协同工作。
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();
}
}
下面的测试代码演示了将最大深度分别限制为 1 级和 2 级。
var obj = new Node {
Name = "one",
Child = new Node {
Name = "two",
Child = new Node {
Name = "three"
}
}
};
var txt1 = SerializeObject(obj, 1);
var txt2 = SerializeObject(obj, 2);
public class Node
{
public string Name { get; set; }
public Node Child { get; set; }
}