本文介绍了IgnoreDataMember属性** ** DE序列化过程中跳过JSON对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档的IgnoreDataMember属性只应该序列化过程中要考虑的。

According to the docs, the IgnoreDataMember attribute is only supposed to be considered during serialization.

这是我所看到的,但是,在正在使用MVC模型绑定*的的* JSON序列化也是如此。

From what I'm seeing, however, MVC model binding is using it during *de*serialization of json as well.

考虑下面的类:

public class Tax
{
    public Tax() { }

    public int ID { get; set; }

    [Required]
    [Range(1, int.MaxValue)]
    [IgnoreDataMember]
    public int PropertyId { get; set; }
}

如果POST / PUT以下JSON字符串到操作方法:

If POST/PUT the following json string to an action method:

{"Position":0,"Description":"State sales tax","Rate":5,"RateIsPercent":true,"PropertyId":1912}

我得到以下验证错误:

I get the following validation error:

{
  "Message": "The request is invalid.",
  "ModelState": {
    "newTax.PropertyId": [
      "The field PropertyId must be between 1 and 2147483647."
    ]
  }
}

无论是 [范围(1,int.MaxValue)] [必需] 属性无效。

如果我删除 [IgnoreDataMember] 属性,一切工作正常。

If I remove the [IgnoreDataMember] attribute, everything works fine.

有没有可以使用它会告诉MVC绑定不要忽视反序列化期间的财产?不同的属性。

Is there a different attribute that can be used which will tell MVC binding not to ignore the property during deserialization?

这只是张贴JSON字符串时发生。如果我发布一个名称/值的字符串,全部的寄托都工作正常。

This only happens when posting a json string. If I post a name/value string, everthing works fine.

推荐答案

答案与Json.net的行为做。这就是模型的结合使用,它的检查 IgnoreDataMember 为序列化和反序列化使其失去作用,我(因为我只想使用它的序列化)。

The answer has to do with the behavior of Json.net. That's what the model binding is using and it's checking IgnoreDataMember for both serialization and deserialization making it useless for me (since I want to only use it for serialization).

JsonIgnore 属性的工作方式完全相同。

The JsonIgnore attribute works exactly the same way.

鉴于此,我脱下我的所有属性忽略的属性,并转而使用json.net的条件序列化方法。

Given that, I pulled all the ignore attributes off my properties and switched to using json.net's conditional serialization methods.

所以基本上添加此为上述物业ID字段:

So basically add this for the above PropertyId field:

public bool ShouldSerializePropertyId() { return false; }

这让反序列化进来,但阻止系列化外出。

That allows deserialization to come in but blocks serialization from going out.

这篇关于IgnoreDataMember属性** ** DE序列化过程中跳过JSON对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 13:05