Json.Net - Explicitly include a single private property

安稳与你 提交于 2019-12-14 02:35:31

问题


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.

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;
        }
    }
}

The "TimeStamp" property's value is injected into the class before it is returned by a service.

I would like this property to survive the json.net serialize/deserialize process so it can be returned to the service.


回答1:


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();
    }
}

The assumption here is that you initialize the TimeStamp property in the constructor since it is a private property.

The serialization logic is the following:

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"
}

with the exception of TimeStamp and CustomerId properties, that would have different values from obvious reasons.



来源:https://stackoverflow.com/questions/27509989/json-net-explicitly-include-a-single-private-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!