在每个类中使用不同的格式序列化同一类中的多个DateTime属性 [英] Serializing multiple DateTime properties in the same class using different formats for each one

查看:59
本文介绍了在每个类中使用不同的格式序列化同一类中的多个DateTime属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个DateTime属性的类.我需要使用不同的格式序列化每个属性.我该怎么做?我试过了:

I have a class with two DateTime properties. I need to serialize each of the properties with a different format. How can I do it? I tried:

JsonConvert.SerializeObject(obj, Formatting.None,
      new IsoDateTimeConverter {DateTimeFormat = "MM.dd.yyyy"});

该解决方案不适用于我,因为它将日期格式应用于所有属性.有什么方法可以序列化具有不同格式的每个DateTime属性?也许有一些属性?

This solution doesn't work for me because it applies date format to all the properties. Is there any way to serialize each DateTime property with different format? Maybe there is some attribute?

推荐答案

NewtonSoft.Json具有难以理解的结构,您可以使用类似以下自定义转换器的方法来完成所需的操作:

NewtonSoft.Json has a structure that's a bit difficult to understand, you can use something like the following custom converter to do what you want:

[TestMethod]
public void Conversion()
{
    var obj = new DualDate()
    {
        DateOne = new DateTime(2013, 07, 25),
        DateTwo = new DateTime(2013, 07, 25)
    };
    Assert.AreEqual("{\"DateOne\":\"07.25.2013\",\"DateTwo\":\"2013-07-25T00:00:00\"}", 
        JsonConvert.SerializeObject(obj, Formatting.None, new DualDateJsonConverter()));
}

class DualDate
{
    public DateTime DateOne { get; set; }
    public DateTime DateTwo { get; set; }
}

class DualDateJsonConverter : JsonConverter
{

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {

        JObject result = new JObject();

        DualDate dd = (DualDate)value;

        result.Add("DateOne", JToken.FromObject(dd.DateOne.ToString("MM.dd.yyyy")));
        result.Add("DateTwo", JToken.FromObject(dd.DateTwo));
        result.WriteTo(writer);
    }

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

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

这篇关于在每个类中使用不同的格式序列化同一类中的多个DateTime属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆