【发布时间】:2021-05-26 14:01:54
【问题描述】:
问题
我正在使用 Blazor WASM,它与使用 ASP.NET Core 构建的 RESTful API 进行通信。 我需要加载带有循环引用的对象。
使用默认序列化设置,这会产生 System.Text.Json.JsonException:
A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger
than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions
to support cycles.
我的尝试
我在服务器上的 Startup.cs 中添加了以下几行到 ConfigureServices():
services.AddControllersWithViews().AddJsonOptions(options => {
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
});
并修改了客户端上的请求:
data = await Http.GetFromJsonAsync<My.Shared.DataObject[]>(
"api/GetDataObjects",
new System.Text.Json.JsonSerializerOptions() {
ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve
}
);
但是客户端在解析响应时抛出System.Text.Json.JsonException:
Cannot parse a JSON object containing metadata properties like '$id' into an array or immutable
collection type. Type 'My.Shared.DataObject[]'.
Path: $.$id | LineNumber: 0 | BytePositionInLine: 7
为什么会这样?如何解决?
【问题讨论】:
-
对创建循环引用的属性使用
[JsonIgnore]属性。当然,您仍然可以让外键通过,而不是实体。 -
能否请edit 分享minimal reproducible example 的问题?但是Cannot parse a JSON object contains metadata properties like '$id' into an array or immutable collection type 似乎可以解释。作为猜测,您有一些在客户端声明为数组的集合类型。尝试将其声明为列表。