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

标签 json vb.net asp.net-web-api

我和这个问题完全一样: 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/

相关文章:

vb.net - 如何选择标签

vb.net - GUI不会相应移动

c# - 暗影 8 : Get reference to DocumentType definition in WebAPI class

asp.net-web-api - 从 web-api 返回到 Swagger-ui 的位置响应头

javascript - 处理 ListView 的嵌套 JSON 数据

javascript - 通过jQuery ajax请求获取数据

javascript - 使用 PapaParse 解析带有 header 的转置 CSV

asp.net-mvc - VB.Net后期绑定(bind)操作不能转换为表达式树

c# - ASP.NET Identity 2.2.1 - 发送带有代码而不是链接的确认电子邮件

php - CodeIgniter 从 Controller 返回数据