【问题标题】:Is there a way to serialize an object to JSON but only include a few properties?有没有办法将对象序列化为 JSON 但只包含一些属性?
【发布时间】:2021-08-25 03:07:08
【问题描述】:

有没有一种方法可以指定使用 JSON 序列化时要包含的属性?

我想做这样的事情:

var string = JSON.serialize(myObject, ["includedProperty1", "includedProp2"]);

这里是关于如何忽略属性的文档:

https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-ignore-properties?pivots=dotnet-5-0

它说要使用 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;。一定要检查这样做的后果是什么

标签: c# json xamarin


【解决方案1】:

据我所知,没有“选择加入”的逻辑。

但既然你说的是“一些”,那么有一个简单的技巧,使用临时匿名类型:

var s = JsonSerializer.Serialize(
    new { myObject.includedProperty1, myObject.includedProp2 });

...

var otherObject = JsonSerializer.Deserialize<OrignalType>(s);

【讨论】:

  • 哈哈,这会奏效。相当巧妙的把戏:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 2015-07-29
  • 2017-01-09
  • 2015-12-30
  • 2012-09-25
相关资源
最近更新 更多