列表中不同值的不同 JsonSerializerSettings

Different JsonSerializerSettings for different values in list

我正在使用此设置序列化 dotnet core 2.2 中的对象列表:

var settings = new JsonSerializerSettings()
{
    DateFormatString = "MM/dd/yyyy h:mm tt"
}

问题是,如果 DateTimes 时间等于 0,我希望它使用“MM/dd/yyyy”序列化和反序列化 DateTimes,但我发现在同一个列表中没有动态方法可以使用两个值(具有不同的 DateTimes次,0 或不是 0)

您可以为此编写自己的 json 转换器。

public class DateTimeStringConverter : JsonConverter
{
    // allowable DateTime formats - update as required
    List<string> DateFormats => new List<string> { "MM/dd/yyyy", "MM/dd/yyyy h:mm tt" };

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var dateStr = (string)reader.Value;
        DateTime date;
        foreach (string format in DateFormats)
        {
            if (DateTime.TryParseExact(dateStr, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                return date;
            }
        }

        throw new JsonException($"{dateStr} as not a valid date string.");
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        DateTime date = DateTime.Parse(value.ToString());
        // Time value of DateTime.Today is always "00:00:00"
        if (date.TimeOfDay == DateTime.Today.TimeOfDay)
        {
            serializer.Serialize(writer, date.ToString("MM/dd/yyyy"));
        }
        else
        {
            serializer.Serialize(writer, date.ToString("MM/dd/yyyy h:mm tt"));
        }
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(DateTime);
    }
}

您可以通过将 DateFormats 更改为 public 列表并在初始化时传递有效的 DateTime 格式来改进 JsonSerializerSettings

然后您可以像这样应用设置:

var settings = new JsonSerializerSettings();
settings.DateParseHandling = DateParseHandling.None;
settings.Converters.Add(new DateTimeStringConverter());

// deserialize
var model = JsonConvert.DeserializeObject<YourClass>(json, settings);

// serialize
var serializedJson = JsonConvert.SerializeObject(model, settings);

这是受此

答案的启发