vb.net 我如何做 JSON 序列化程序忽略导航属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26162902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:18:40  来源:igfitidea点击:

How can I do JSON serializer ignore navigation properties?

jsonvb.netasp.net-web-api

提问by Carlos

I am exactly in the same case that this question: How do I make JSON.NET ignore object relationships?

我与这个问题完全相同: How do I make JSON.NET ignore object Relations?

I see the proposed solution and I know I must use a Contract Revolver, and I also see the code of the Contract Resolver, but I do not know how to use it.

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

  • Should I use it in the WebApiConfig.vb?
  • Should I modify my Entity Model anyway?
  • 我应该在 WebApiConfig.vb 中使用它吗?
  • 我应该修改我的实体模型吗?

回答by RAM

I hope this helps:

我希望这有帮助:

A)

一种)

If you have created your models manually (without Entity Framework/EF), mark the relation properties as virtualfirst.

如果您手动创建了模型(没有Entity Framework/ EF),请将关系属性标记为virtual第一个。

If your models were created by EF, It has already done it for you and each Relation Propertyis marked as virtual, as seen below:

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

enter image description here

在此处输入图片说明

Sample class:

Sample class:

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)

乙)

Those relation properties can now be ignored by the JSONserializer by using the following ContractResolverfor JSON.NETis custom code:

这些关系属性现在可以JSON通过使用以下ContractResolverfor JSON.NETis 自定义代码被序列化程序忽略:

CustomResolver:

CustomResolver:

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)

C)

Finally, to make JSON.NETuse the above ContractResolver, set it up like this:

最后,为了JSON.NET使用上面的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
// }

Now, all the navigation (relation) properties [virtualproperties] will be ignored automatically except you keep some of them my determine them in your code.

现在,所有导航(关系)属性 [ virtualproperties] 将被自动忽略,除非您在代码中保留其中一些由我确定。

Live DEMO

现场演示



Thanks from @BrianRogersfor his answer here.

感谢@BrianRogers这里的回答。