c# - 使用 JSON.Net 解析 ISO 持续时间

标签 c# asp.net-web-api json.net

我在 Global.asax.cs 中有一个具有以下设置的 Web API 项目:

var serializerSettings = new JsonSerializerSettings
    {
        DateFormatHandling = DateFormatHandling.IsoDateFormat, 
        DateTimeZoneHandling = DateTimeZoneHandling.Utc
    };

serializerSettings.Converters.Add(new IsoDateTimeConverter());

var jsonFormatter = new JsonMediaTypeFormatter { SerializerSettings = serializerSettings };
jsonFormatter.MediaTypeMappings.Add(GlobalConfiguration.Configuration.Formatters[0].MediaTypeMappings[0]);

GlobalConfiguration.Configuration.Formatters[0] = jsonFormatter;

WebApiConfig.Register(GlobalConfiguration.Configuration);

尽管如此,Json.Net 还是无法解析 ISO durations .

它抛出这个错误:

Error converting value "2007-03-01T13:00:00Z/2008-05-11T15:30:00Z" to type 'System.TimeSpan'.

我正在使用 Json.Net v4.5。

我尝试了不同的值,例如“P1M”和 wiki 页面上列出的其他值,但没有成功。

那么问题是:

  1. 我是不是漏掉了什么?
  2. 或者我是否必须编写一些自定义格式化程序?

最佳答案

我遇到了同样的问题,现在正在使用这个自定义转换器将 .NET TimeSpans 转换为 ISO 8601 持续时间字符串。

public class TimeSpanConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var ts = (TimeSpan) value;
        var tsString = XmlConvert.ToString(ts);
        serializer.Serialize(writer, tsString);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
        JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
        {
            return null;
        }

        var value = serializer.Deserialize<String>(reader);
        return XmlConvert.ToTimeSpan(value);
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof (TimeSpan) || objectType == typeof (TimeSpan?);
    }
}

关于c# - 使用 JSON.Net 解析 ISO 持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12633588/

相关文章:

c# - 动态方法预链接

c# - 使用动态 LINQ(或泛型)查询/筛选 Azure 表

entity-framework - 在 Visual Studio 2012 中使用 EF 脚手架创建新的 Web API Controller 时出现 "Object reference not set to an instance of an object"

C#多线程事务导致异常

c# - 当文本框上的 iframe 控件具有焦点时,如何保持页面的滚动位置?

c# - 如何将文件放入 HttpResponseMessage 内容?

c# - 自定义调用 Action 的 ASP Web API Json 序列化

c# - 在 ASP.NET MVC 中设置默认的 JSON 序列化程序

c# - JsonPropertyAttribute 中的 JSON.NET NullValueHandling 未按预期工作

.net - Google 的 OpenIDConnect 返回一个无法解析的 Base64 token