仅为某些属性存储类型
Store types only for certain properties
我的树很深,节点如下:
class Node {
public string Name { get; }
public IA A { get; set; }
public IReadOnlyList<Node> Children { get; }
[JsonConstructor]
public Node(string name, List<Node> children) { ... }
}
我正在尝试减少存储序列化数据所需的 space 数量。
我希望序列化程序能够根据构造函数中的相应参数找出 Children
的类型。是否可以只为 属性 A
存储类型而不为 Children
存储类型?
现在我使用以下内容,但就 space 而言,这是非常昂贵的:
JsonConvert.SerializeObject(tree, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });
将Children
序列化为
"Children": {
"$type": "System.Collections.Generic.List`1[[Very.Long.Node, Very.Long.Structure]], mscorlib",
...
真实类型非常复杂,因此非常感谢每个字段的解决方案。
尝试将 [JsonProperty]
属性添加到您的 A
属性,并在那里设置 TypeNameHandling
。然后从 JsonSerializerSettings
中删除 TypeNameHandling
(如果不需要任何其他设置,则完全省略 JsonSerializerSettings
)。
换句话说:
class Node {
public string Name { get; }
[JsonProperty(TypeNameHandling = TypeNameHandling.Auto)] // add this
public IA A { get; set; }
public IReadOnlyList<Node> Children { get; }
[JsonConstructor]
public Node(string name, List<Node> children) { ... }
}
然后像这样序列化:
var json = JsonConvert.SerializeObject(tree);
这是一个往返演示:https://dotnetfiddle.net/c8LvTi
我的树很深,节点如下:
class Node {
public string Name { get; }
public IA A { get; set; }
public IReadOnlyList<Node> Children { get; }
[JsonConstructor]
public Node(string name, List<Node> children) { ... }
}
我正在尝试减少存储序列化数据所需的 space 数量。
我希望序列化程序能够根据构造函数中的相应参数找出 Children
的类型。是否可以只为 属性 A
存储类型而不为 Children
存储类型?
现在我使用以下内容,但就 space 而言,这是非常昂贵的:
JsonConvert.SerializeObject(tree, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });
将Children
序列化为
"Children": {
"$type": "System.Collections.Generic.List`1[[Very.Long.Node, Very.Long.Structure]], mscorlib",
...
真实类型非常复杂,因此非常感谢每个字段的解决方案。
尝试将 [JsonProperty]
属性添加到您的 A
属性,并在那里设置 TypeNameHandling
。然后从 JsonSerializerSettings
中删除 TypeNameHandling
(如果不需要任何其他设置,则完全省略 JsonSerializerSettings
)。
换句话说:
class Node {
public string Name { get; }
[JsonProperty(TypeNameHandling = TypeNameHandling.Auto)] // add this
public IA A { get; set; }
public IReadOnlyList<Node> Children { get; }
[JsonConstructor]
public Node(string name, List<Node> children) { ... }
}
然后像这样序列化:
var json = JsonConvert.SerializeObject(tree);
这是一个往返演示:https://dotnetfiddle.net/c8LvTi