如何使用不同的格式为每个对象列表中的多个DateTime属性序列化?

时间:2016-11-17 16:32:40

标签: json list datetime serialization json.net

我有这个对象结构:

public class FirstClassResponse
{
    public int draw { get; set; }
    public int recordsTotal { get; set; }
    public int recordsFiltered { get; set; }
    public List<SecondClass> data { get; set; }
}

public class SecondClass
{
    public long Id { get; set; }
    public System.DateTime InsertionDate { get; set; }
    public System.DateTime DeletionDate { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string ZipCode { get; set; }
    public string EmailAddress { get; set; }
    public string PhoneNumber { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public System.DateTime LastUpdate { get; set; }
}

我需要序列化FirstClassResponse,目前我使用Json.NET。但InsertionDateDeletionDateLastUpdate具有自己的序列化DateTime格式。

我将此post作为参考,但是,我仍然想知道如何在我的情况下实现它,它在List中具有多个日期时间属性。

public class FirstClassResponseJSONConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {

        JObject result = new JObject();

        FirstClassResponse data = (SubContractorResponse)value;

        //result.Add("data.LastUpdate", JToken.FromObject(data.data..ToString("MM.dd.yyyy")));
        //result.Add("data.DeletionDate", JToken.FromObject(data.DateTwo));
        //still don't have any idea for this part..

        result.WriteTo(writer);
    }

    // Other JsonConverterMethods
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(SubContractorResponse);
    }

    public override bool CanWrite
    {
        get
        {
            return true;
        }
    }
    public override bool CanRead
    {
        get
        {
            return false;
        }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

0 个答案:

没有答案