【问题标题】:Parsing ISO Duration with JSON.Net使用 JSON.Net 解析 ISO 持续时间
【发布时间】:2012-09-19 23:01:47
【问题描述】:

我在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

它抛出这个错误:

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

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

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

所以问题是:

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

【问题讨论】:

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


    【解决方案1】:

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

    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 解析器中使用 XmlConvert 感觉有点奇怪,但效果很好。
    • 是的,真正奇怪的是,使用 Xml 函数的非常相似的方法也是您在 Java 中也需要使用的方法。
    猜你喜欢
    • 2014-07-16
    • 2014-08-16
    • 2021-02-16
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2021-12-12
    • 2010-11-11
    相关资源
    最近更新 更多