我有一个带有两个DateTime属性的类。我需要使用不同的格式序列化每个属性。我该怎么做?我试过了:
JsonConvert.SerializeObject(obj, Formatting.None, new IsoDateTimeConverter {DateTimeFormat = "MM.dd.yyyy"});
该解决方案不适用于我,因为它将日期格式应用于所有属性。有什么方法可以序列化具有不同格式的每个DateTime属性?也许有一些属性?
NewtonSoft.Json 具有难以理解的结构,您可以使用以下自定义转换器之类的工具来执行所需的操作:
NewtonSoft.Json
[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(); } }