我该怎么办JSON序列忽略导航性质? [英] How can I do JSON serializer ignore navigation properties?

查看:179
本文介绍了我该怎么办JSON序列忽略导航性质?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是完全一样的情况下,这个问题:
<一href=\"http://stackoverflow.com/questions/21292010/how-do-i-make-json-net-ignore-object-relationships\">How让我的JSON.NET忽略对象关系

I am exactly in the same case that this question: How Do I Make JSON.NET Ignore Object Relationships

我看到了建议的解决方案,我知道我必须使用合同左轮手枪,我也看到了合同解析器的code,但我不知道如何使用它。

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.


  • 我应该用它在WebApiConfig.vb?

  • 我应该反正修改我的实体模型?

请,我将非常高兴与方法的任何帮助。

Please, I would be very glad of any help with the approach.

感谢您

推荐答案

我希望这种方式帮助:

如果您的模型创建的基础上,实体框架,你可以看到每个相关特性标记为虚拟

If your models created base on Entity Framework, you can see each Relation Property marked as Virtual.

在这里输入的形象描述

此外,如果你做手工的模型(无 EF ),你可以标记的关系属性虚拟来忽略它们在 JSON 通过下面的示例codeS序列化:

Also if you makes your models manually (without EF), you can mark the relation properties as Virtual to ignore them in JSON serialization by the following sample codes:

class CustomResolver : DefaultContractResolver
{
    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)
            {
                prop.ShouldSerialize = obj => false;
            }
        }
        return prop;
    }
}

现在使用上述 ContractResolver 是这样的:

Now use above ContractResolver like this:

 // Serializer settings
    JsonSerializerSettings settings = new JsonSerializerSettings();
    settings.ContractResolver = new CustomResolver();
    settings.PreserveReferencesHandling = PreserveReferencesHandling.None;
    settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    settings.Formatting = Formatting.Indented;

    // Do the serialization and output to the console
    string json = JsonConvert.SerializeObject(pc, settings);

在结果所有的导航(关系)的属性[虚拟财产]将忽略...

In the result all the navigation (relation) properties [virtual properties] will be ignore...

通过 @BrianRogers 感谢他的回答<一个href=\"http://stackoverflow.com/questions/21292010/how-do-i-make-json-net-ignore-object-relationships#21295181\">here.

这篇关于我该怎么办JSON序列忽略导航性质?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆