使用.Net和Newtonsoft,我如何在序列化时隐藏一个模型属性,但是,能够填充该属性并利用传递的值。
例如。
[JsonIgnore]
public Int16 Value { get; set; }这隐藏了输出上的属性,但是,我不能设置模型POST的值。如何在输出时隐藏属性,但允许在POST或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"
}商业逻辑:
型号:
namespace Library.Models.Bible
{
public class BibleModel : IPopulatable<BibleModel, DataTable>, IPopulatable<BibleModel, DataRow>
{
public Int32? ID { get; set; }
[MinLength(4, ErrorMessage = "Bible name must be between 4-100 characters")]
[MaxLength(100, ErrorMessage = "Bible name must be between 4-100 characters")]
public String Name { get; set; }
[MinLength(3, ErrorMessage = "Bible abbreviation must be between 3-9 characters")]
[MaxLength(9, ErrorMessage = "Bible abbreviation must be between 3-9 characters")]
[ValidateBibleAbbreviationExists]
public String Abbreviation { get; set; }
[MaxLength(250, ErrorMessage = "Publisher may not exceed 250 characters")]
public String Publisher { get; set; }
[MaxLength(3000, ErrorMessage = "Copyright may not exceed 3000 characters")]
public String Copyright { get; set; }
[MaxLength(3000, ErrorMessage = "Notes may not exceed 3000 characters")]
public String Notes { get; set; }
[EnumDataType(typeof(Enums.eTxtDir), ErrorMessage = "Text direction does not exist. Allowed values: LTR, RTL")]
public String TextDirection { get; set; }
[JsonIgnore]
public Int16 Active { get; set; } = 1;
public BibleModel Populate(DataTable dT)
{
if (dT != null && dT.Rows.Count > 0)
return Populate(dT.Rows[0]);
return null;
}
public BibleModel Populate(DataRow ro)
{
if(ro != null)
{
this.ID = Convert.ToInt32(ro["Bible_ID"]);
this.Name = ro["Name"].ToString();
this.Abbreviation = ro["Abbr"].ToString();
this.Publisher = ro["Publisher"].ToString();
this.Copyright = ro["Copyright"].ToString();
this.Notes = ro["Notes"].ToString();
this.TextDirection = ro["TxtDir"].ToString();
return this;
}
return null;
}
}发布于 2018-07-04 07:55:19
有几种可能性(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;}
}https://stackoverflow.com/questions/51165216
复制相似问题