gpt4 book ai didi

c# - 如何在C#中将JSON对象序列化或反序列化到一定深度?

转载 作者:可可西里 更新时间:2023-11-01 02:58:36 24 4
gpt4 key购买 nike

我只想要对象的第一个深度级别(我不想要任何子对象)。我愿意使用任何可用的库。大多数库只会在达到递归深度时抛出异常,而不是直接忽略。如果这不可能,是否有办法忽略给定特定数据类型的特定成员的序列化?

编辑:假设我有一个这样的对象:

class MyObject
{
String name = "Dan";
int age = 88;
List<Children> myChildren = ...(lots of children with lots of grandchildren);
}

我想删除任何子项(甚至是复杂类型)以返回这样的对象:

class MyObject
{
String name = "Dan";
int age = 88;
List<Children> myChildren = null;
}

最佳答案

这在 Json.NET 中是可能的在 JsonWriter 之间使用一些协调和序列化程序的 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; }
}

关于c# - 如何在C#中将JSON对象序列化或反序列化到一定深度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10453127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com