【发布时间】:2021-08-25 03:07:08
【问题描述】:
有没有一种方法可以指定使用 JSON 序列化时要包含的属性?
我想做这样的事情:
var string = JSON.serialize(myObject, ["includedProperty1", "includedProp2"]);
这里是关于如何忽略属性的文档:
它说要使用 Json Ignore 元数据,但我的模型有大约 50 个不同的字段。它可能有更多。
所以,我想忽略除少数几个属性之外的所有属性,还是我必须对所有属性使用 [JSonIgnore]?
这是我目前所拥有的:
using System.Text.Json;
string fileName = "project.json";
var options = new JsonSerializerOptions() { };
var isValid = NSJsonSerialization.IsValidJSONObject(model);
// error on this line
string value = JsonSerializer.Serialize(model);
给出一个错误:
检测到可能的对象循环。这可能是由于 循环或如果对象深度大于最大允许深度 64. 考虑使用 ReferenceHandler.Preserve 支持循环的 JsonSerializerOptions。
这是我针对该错误所做的尝试:
var options = new JsonSerializerOptions() { };
options.ReferenceHandler = "Ignore"; // not allowed value
【问题讨论】:
-
JsonIgnore需要 .NET 5.0 或 .NET Core 3.0 docs.microsoft.com/en-us/dotnet/api/… -
我刚刚添加了使用 System.Text.Json.Serialization;并且 JsonIgnore 没有显示错误
-
@AkshayGaonkar 有趣。看起来我可以设置一个标志来忽略引用,但它给了我一个错误。 var options = new JsonSerializerOptions() { }; options.ReferenceHandler = "忽略";
-
那是Newtonsoft.Json 试试那个适用于System.Text.Json
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;。一定要检查这样做的后果是什么