C#.Net Newtonsoft JSON不序列化属性,但在Json Post中阅读

时间:2018-07-04 03:06:16

标签: c# .net json.net

使用.Net和Newtonsoft Json,如何在序列化时隐藏模型属性,但是,能够填充该属性并利用传递的值。

例如

1.0 + (2.0 + 2.0) = 5.0
(2.0 + 2.0) + 1.0 = 5.0
1.0 + (2.0 * 2.0) = 5.0
(2.0 * 2.0) + 1.0 = 5.0
1.0 + (2.0 ^ 2.0) = 5.0
(2.0 ^ 2.0) + 1.0 = 5.0
2.0 + (2.0 + 1.0) = 5.0
(2.0 + 1.0) + 2.0 = 5.0
2.0 + (1.0 + 2.0) = 5.0
(1.0 + 2.0) + 2.0 = 5.0

10 unique solutions were found

这将隐藏输出中的属性,但是,我无法在模型POST上设置该值。如何隐藏输出中的属性,但允许在POST或PUT请求上设置该属性?

POST示例:

[JsonIgnore]
public Int16 Value { get; set; }

PUT示例:

{
    "Name": "King James Version",
    "Abbreviation" : "kjv",
    "Publisher": "Public Domain",
    "Copyright": "This is the copyright",
    "Notes": "This is the notes.",
    "TextDirection" : "LTR"
}

业务逻辑:

  1. 不应在POST请求中传递ID,如果传递ID,则会将其忽略。
  2. 缩写是POST请求所必需的,并将使用自定义的Validation Filter属性针对数据库进行验证。
  3. 不能在PUT请求中传递缩写,因为该字段/属性无法更新。
  4. 必须在PUT请求中传递ID,以在自定义验证程序中标识它是PUT请求而不是POST请求。

型号:

{
    "ID" : 1,
    "Name": "King James Version",
    "Abbreviation" : "kjv",
    "Publisher": "Public Domain",
    "Copyright": "This is the copyright",
    "Notes": "This is the notes.",
    "TextDirection" : "LTR"
}

1 个答案:

答案 0 :(得分:1)

有几种可能性(https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm

1)编写自定义合同解析器

class MyContractResolver: DefaultContractResolver 
{


  protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);
            property.ShouldSerialize = String.Compare(property.PropertyName, "Value") != 0;
            return property;
        }
}

2)向您的班级添加ShouldSerialize...方法

 class MyClass {

     public Int16 Value {get;set;}
     public bool ShouldSerializeValue() {return false;}
 }