c# - JSON .NET 不反序列化 Refs
问题描述
我有以下最小示例:
class Program
{
static void Main()
{
var plan = new Plan
{
Steps =
{
new Step
{
Contexts =
{
new Context
{
Name = "1"
},
new Context
{
Name = "2"
}
}
}
}
};
var settings = new JsonSerializerSettings
{ PreserveReferencesHandling = PreserveReferencesHandling.Objects, Formatting = Formatting.Indented };
var json = JsonConvert.SerializeObject(plan, settings);
var deserialized = JsonConvert.DeserializeObject<Plan>(json, settings);
}
}
class Plan
{
public IEnumerable AllContexts => Steps.SelectMany(i => i.Contexts);
[JsonProperty(Order = int.MaxValue)]
public ICollection<Step> Steps { get; set; } = new List<Step>();
}
class Step
{
public ICollection<Context> Contexts { get; set; } = new List<Context>();
}
class Context
{
public string Name { get; set; }
}
在此示例deserialized
中,反序列化时已丢失其引用,并且deserialized.AllContexts
是 2 个空值的集合。
我可以通过更改为来完成此工作,[JsonProperty(Order = int.MaxValue)]
因此[JsonProperty(Order = int.MinValue)]
首先对 Steps 进行序列化 - 但在我的场景中,我希望实际的 JSON 在平面AllContexts
数组上具有其所有属性,并且 Steps 仅具有$ref
如下所示的 s:
{
"$id": "1",
"AllContexts": [
{
"$id": "2",
"Name": "1"
},
{
"$id": "3",
"Name": "2"
}
],
"Steps": [
{
"$id": "4",
"Contexts": [
{
"$ref": "2"
},
{
"$ref": "3"
}
]
}
]
}
这似乎是 JSON .NET 中的一个错误 - 有没有办法解决它?
解决方案
推荐阅读
- javascript - 使用 $(document).ready(function() 更改标签的文本
- javascript - 为什么服务器上的“窗口”编码问题上的“atob”而不是本地的(laravel 代客)?
- php - 文件上传无法插入mysqli数据库
- android - 使用 ViewPager 的自动滑块图像
- javascript - 解释一系列箭头运算符
- python - Python:在散点图中查找多条线性趋势线
- spring - CSS + Thymleaf - CSS 不反映在页面上
- html - 输入表单中的自动数字空间
- sql - 计算一个案例中的案例数量
- ios - 将屏幕从纵向转换为横向它在从左到右旋转时不会保持横向,反之亦然