gpt4 book ai didi

json - 我怎样才能让 JSON 序列化程序忽略导航属性?

转载 作者:太空宇宙 更新时间:2023-11-03 14:44:34 24 4
gpt4 key购买 nike

我和这个问题完全一样: How do I make JSON.NET ignore object relationships?

我看到了建议的解决方案,我知道我必须使用 Contract Revolver,我也看到了 Contract Resolver 的代码,但我不知道如何使用它。

  • 我应该在 WebApiConfig.vb 中使用它吗?
  • 我是否应该修改我的实体模型?

最佳答案

这是一个很有用的问题👍,希望对您有所帮助:

一)

如果您手动创建了模型(没有 Entity Framework),请首先将关系属性标记为虚拟

如果您的模型是由 EF 创建的,它已经为您完成了并且每个 Relation Property 都被标记为 virtual,如图所示下面:

enter image description here

示例类:

public class PC
{
public int FileFolderId {get;set;}

public virtual ICollection<string> Libs { get; set; }
public virtual ICollection<string> Books { get; set; }
public virtual ICollection<string> Files { get; set; }
}

B)

JSON 序列化程序现在可以忽略这些关系属性,方法是使用以下 JSON.NETContractResolver:

自定义解析器:

class CustomResolver : DefaultContractResolver
{
private readonly List<string> _namesOfVirtualPropsToKeep=new List<string>(new String[]{});

public CustomResolver(){}

public CustomResolver(IEnumerable<string> namesOfVirtualPropsToKeep)
{
this._namesOfVirtualPropsToKeep = namesOfVirtualPropsToKeep.Select(x=>x.ToLower()).ToList();
}

protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty prop = base.CreateProperty(member, memberSerialization);
var propInfo = member as PropertyInfo;
if (propInfo != null)
{
if (propInfo.GetMethod.IsVirtual && !propInfo.GetMethod.IsFinal
&& !_namesOfVirtualPropsToKeep.Contains(propInfo.Name.ToLower()))
{
prop.ShouldSerialize = obj => false;
}
}
return prop;
}
}

C)

最后,要轻松序列化您的模型,请使用上面的ContractResolver。像这样设置:

// -------------------------------------------------------------------
// Serializer settings
JsonSerializerSettings settings = new JsonSerializerSettings
{
// ContractResolver = new CustomResolver();
// OR:
ContractResolver = new CustomResolver(new []
{
nameof(PC.Libs), // keep Libs property among virtual properties
nameof(PC.Files) // keep Files property among virtual properties
}),
PreserveReferencesHandling = PreserveReferencesHandling.None,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Formatting = Formatting.Indented
};

// -------------------------------------------------------------------
// Do the serialization and output to the console
var json = JsonConvert.SerializeObject(new PC(), settings);
Console.WriteLine(json);

// -------------------------------------------------------------------
// We can see that "Books" filed is ignored in the output:
// {
// "FileFolderId": 0,
// "Libs": null,
// "Files": null
// }

现在,所有导航(关系)属性 [virtual properties] 都将被自动忽略,除非您通过在代码中确定它们来保留其中一些。😎

Live DEMO


感谢 @BrianRogers他的回答here .

关于json - 我怎样才能让 JSON 序列化程序忽略导航属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55117506/

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