使用 JSON.Net 解析 ISO 持续时间 [英] Parsing ISO Duration with JSON.Net

查看:30
本文介绍了使用 JSON.Net 解析 ISO 持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Web API project with the following settings in Global.asax.cs:

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 持续时间.

Despite all this, Json.Net cannot parse ISO durations.

它抛出这个错误:

将值2007-03-01T13:00:00Z/2008-05-11T15:30:00Z"转换为错误输入System.TimeSpan".

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

我使用的是 Json.Net v4.5.

I'm using Json.Net v4.5.

我尝试了不同的值,例如P1M"和维基页面上列出的其他值,但都没有成功.

I've tried different values such as "P1M" and others listed on the wiki page with no luck.

所以问题是:

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

推荐答案

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

I ran into the same problem and am now using this custom converter to Convert .NET TimeSpans to ISO 8601 Duration strings.

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?);
    }
}

这篇关于使用 JSON.Net 解析 ISO 持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆