Json.Net-明确包含一个私有财产 [英] Json.Net - Explicitly include a single private property
问题描述
我有一个对象(ViewModel),其中有一个私有属性,其中包含有关模型的一些元数据.我想在对象的序列化/反序列化中明确包含此私有属性.
I have an object (ViewModel) in which I have a private property that holds some meta-data about the model. I would like to explicitly include this private property in the serializing/deserializing of the object.
是否可以添加到属性中的Json.Net属性?
Is there a Json.Net Attribute I can add to the property?
public class Customer
{
private string TimeStamp { get; set; }
public Guid CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Name
{
get
{
return FirstName + " " + LastName;
}
}
}
"TimeStamp"属性的值在服务返回之前被注入到类中.
The "TimeStamp" property's value is injected into the class before it is returned by a service.
我希望此属性在json.net序列化/反序列化过程中继续存在,以便可以将其返回给服务.
I would like this property to survive the json.net serialize/deserialize process so it can be returned to the service.
推荐答案
如果要序列化/反序列化privete属性,请使用JsonProperty
属性对其进行修饰.您的课程应如下所示:
If you want to serialize/deserialize a privete property, decorate it with the JsonProperty
attribute. Your class should look like this:
public class Customer
{
[JsonProperty]
private string TimeStamp { get; set; }
public Guid CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Name
{
get
{
return FirstName + " " + LastName;
}
}
public Customer()
{
TimeStamp = DateTime.Now.Ticks.ToString();
}
}
这里的假设是您在构造函数中初始化TimeStamp
属性,因为它是私有属性.
The assumption here is that you initialize the TimeStamp
property in the constructor since it is a private property.
序列化逻辑如下:
var customer = new Customer
{
CustomerId = Guid.NewGuid(),
FirstName = "Jonh",
LastName = "Doe"
};
var json = JsonConvert.SerializeObject(customer, Formatting.Indented);
Console.WriteLine(json);
输出应类似于以下内容:
The output should be similar to the following one:
{
"TimeStamp": "635543531529938160",
"CustomerId": "08537598-73c0-47d5-a320-5e2288989498",
"FirstName": "Jonh",
"LastName": "Doe",
"Name": "Jonh Doe"
}
除了TimeStamp
和CustomerId
属性,由于明显的原因,它们的值将不同.
with the exception of TimeStamp
and CustomerId
properties, that would have different values from obvious reasons.
这篇关于Json.Net-明确包含一个私有财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!