gpt4 book ai didi

c# - 有时想要序列化 ​​Json 包含 [JsonIgnore]

转载 作者:太空宇宙 更新时间:2023-11-03 13:40:57 25 4
gpt4 key购买 nike

我有 95% 的类不想序列化某些否定属性。所以我使用 [JsonIgnore] 属性和 Newtonsoft.Json,它工作正常。

但是,我只有少数方法想要返回包含来自 [JsonIgnore] 的属性的 JSON。我该怎么做?

谢谢大家

public class SubCatalog
{
[Key]
public int Id { get; set; }

[ForeignKey("Catalog")]
public int CatalogId { get; set; }
public string Name { get; set; }

[JsonIgnore]
public virtual Catalog Catalog { get; set; }
[JsonIgnore]
public virtual IList<Item> Items { get; set; }
}

使用这种方法,我想在实体中包含所有属性。

public HttpResponseMessage GetSubCatalogs(int id)
{
var list = _uow.SubCatalogs.GetByCatalogId(id);
var json = JsonConvert.SerializeObject(list,
Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});

return new HttpResponseMessage()
{
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};
}

最佳答案

您可以使用 IContractResolver

public class IncludeIgnored : DefaultContractResolver
{
private readonly bool _includeIgnored;

public IncludeIgnored(bool includeIgnored)
{
_includeIgnored = includeIgnored;
}

protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

foreach (var item in properties)
{
item.Ignored = !_includeIgnored;
}

return properties;
}
}

然后当你调用你的序列化程序时

var serializedObject= JsonConvert.SerializeObject(myObject, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new IncludeIgnored(true) });

关于c# - 有时想要序列化 ​​Json 包含 [JsonIgnore],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17051909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com