使用.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"
}
业务逻辑:
型号:
{
"ID" : 1,
"Name": "King James Version",
"Abbreviation" : "kjv",
"Publisher": "Public Domain",
"Copyright": "This is the copyright",
"Notes": "This is the notes.",
"TextDirection" : "LTR"
}
答案 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;}
}