Serializing multiple DateTime properties in the same class using different formats for each one(序列化同一类中的多个 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 属性,每个属性使用不同的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:序列化同一类中的多个 DateTime 属性,每个属性使用不同的格式
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
