我尝试创建自定义DateTime转换器失败。 问题:我有很多要序列化的对象,其中包含DateTime的一些包含DateTime.MinValue的属性。我想将它序列化为null。但是我要求在对象内部装饰正确的所有解决方案(我不能这样做) 我在下面找到的其他解决方案是创建转换器,据我所知,这个转换器只能显式返回DateTime对象,而不能在其他对象中返回。 请帮忙。
public class DateTimeConverter : JsonConverter
{
private readonly Type[] types;
public DateTimeConverter(params Type[] types)
{
this.types = types;
}
public override bool CanConvert(Type objectType)
{
return types.Any(t => t == objectType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
if (value is DateTime && value.Equals(DateTime.MinValue))
{
t = JToken.FromObject(null);
t.WriteTo(writer);
}
else
{
t.WriteTo(writer);
}
}
else
{
if (value.Equals(DateTime.MinValue)) {
t = JToken.FromObject(null);
t.WriteTo(writer);
}
else {
t.WriteTo(writer);
}
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
}
答案 0 :(得分:4)
我认为你过分复杂了。您的转换器应该只担心转换日期值,而不是转换可能包含日期值的对象。只要在任何其他对象内遇到日期,序列化器就会自然地调用转换器。
这是一个简单的转换器,可以执行您想要的操作:
public class MinDateToNullConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
// This converter handles date values directly
return (objectType == typeof(DateTime));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// The CanConvert method guarantees the value will be a DateTime
DateTime date = (DateTime)value;
if (date == DateTime.MinValue)
{
writer.WriteNull();
}
else
{
writer.WriteValue(date);
}
}
public override bool CanRead
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
这是一个演示,显示转换器在整个嵌套的对象层次结构中的日期工作:
class Program
{
static void Main(string[] args)
{
Example example = new Example
{
Date1 = new DateTime(2014, 2, 2),
Date2 = DateTime.MinValue,
Inner = new Inner
{
DateA = DateTime.MinValue,
DateB = new DateTime(1954, 1, 26)
},
MoreDates = new List<DateTime>
{
new DateTime(1971, 11, 15),
DateTime.MinValue
}
};
// Set up the serializer to use our date converter
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new MinDateToNullConverter());
settings.Formatting = Formatting.Indented;
string json = JsonConvert.SerializeObject(example, settings);
Console.WriteLine(json);
}
}
class Example
{
public DateTime Date1 { get; set; }
public DateTime Date2 { get; set; }
public Inner Inner { get; set; }
public List<DateTime> MoreDates { get; set; }
}
class Inner
{
public DateTime DateA { get; set; }
public DateTime DateB { get; set; }
}
输出:
{
"Date1": "2014-02-02T00:00:00",
"Date2": null,
"Inner": {
"DateA": null,
"DateB": "1954-01-26T00:00:00"
},
"MoreDates": [
"1971-11-15T00:00:00",
null
]
}
答案 1 :(得分:1)
当转换器实现CanConvert
(和你的)时,你可以将其添加到序列化设置:
JsonConvert.SerializeObject(foo, new JsonSerializerSettings {
Converters = {
new DateTimeConverter()
}
});
这样,它将应用于它支持的所有对象。
答案 2 :(得分:0)
找到我的问题的答案。实际上我在JsonSerializer设置中有2个转换器。 我注意到当我删除包含DateTime MinValue属性的对象A上的转换器时,我的序列化器工作正常。这让我明白DateTime转换为null不能在其他转换器下工作。所以我所做的是手动转换对象A转换器,而不是完全干净的解决方案,我希望DateTimeToNull转换器也可以在A转换器内工作。 这是我在A转换器中所做的:
public class AConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(A));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken jToken = JToken.FromObject(value);
JObject jObject = (JObject)jToken;
A aInfo = (A) value;
string statusString = aInfo.Status == null ? string.Empty : SomeUtil.GetStateString((State)aInfo.Status.State, aInfo.Status.Downloading);
jObject.AddFirst(new JProperty("MachineState", statusString));
if (aInfo.UploadTime == DateTime.MinValue) {
jObject.Remove("UploadTime");
jObject.Add(new JProperty("UploadTime", null));
}
jObject.WriteTo(writer);
}
public override bool CanRead
{
get
{
return false;
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException("It's OK!");
}
}