c# - 使用 JSON.NET 和 NodaTime 从 JSON 反序列化 LocalTime 导致 NodaTime.Text.UnparsableValueException

标签 c# json json.net deserialization nodatime

我在将时间值反序列化为 LocalTime 时遇到问题 - 当然,我是 NodaTime 的新手。我想导入一个以“HH:mm”格式列出时间的 Web 服务结果。除非我使用“hh:mm:ss.fff”格式的时间,否则我会遇到异常。有没有一种方法可以指定不同的模式并让“HH:mm”起作用?

请看这段代码

using System;
using System.Collections.Generic;

using Newtonsoft.Json;
using NodaTime;
using NodaTime.Serialization.JsonNet;
using NodaTime.Text;    // Required for LocalTimePattern
namespace TestNodaTime
{
    class MyObject
    {
        [JsonProperty("var1")]
        public int MyProperty { get; set; }

        [JsonProperty("time")]
        public LocalTime MyTime { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string serializedObject1 = "[{\"var1\":\"42\",\"time\":\"01:02:03.004\"}]";
            string serializedObject2 = "[{\"var1\":\"42\",\"time\":\"01:02\"}]";

            JsonSerializerSettings jss = new JsonSerializerSettings();
            jss.ConfigureForNodaTime(DateTimeZoneProviders.Bcl);

            // This works - the pattern is "hh:mm:ss.fff"
            MyObject mo1 = JsonConvert.DeserializeObject<List<MyObject>>(serializedObject1, jss)[0];

            // This causes an exception  - the pattern is "HH:mm"
            MyObject mo2 = JsonConvert.DeserializeObject<List<MyObject>>(serializedObject2, jss)[0];
            /*
             * An unhandled exception of type 'NodaTime.Text.UnparsableValueException' occurred in Newtonsoft.Json.dll
             * Additional information: The value string does not match a quoted string in the pattern. 
             * Value being parsed: '01:02^'. (^ indicates error position.)
             */
        }
    }
}

抛出异常:

NodaTime.Text.UnparsableValueException was unhandled
  HResult=-2146233033
  Message=The value string does not match a quoted string in the pattern. Value being parsed: '01:02^'. (^ indicates error position.)
  Source=NodaTime
  StackTrace:
       at NodaTime.Text.ParseResult`1.GetValueOrThrow()
       at NodaTime.Text.ParseResult`1.get_Value()
       at NodaTime.Serialization.JsonNet.NodaPatternConverter`1.ReadJsonImpl(JsonReader reader, JsonSerializer serializer)
       at NodaTime.Serialization.JsonNet.NodaConverterBase`1.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, String id)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
       at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
       at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
       at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
       at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
       at TestNodaTime.Program.Main(String[] args)
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

最佳答案

您需要删除它在调用 ConfigureForNodaTime 时添加的默认转换器.这些转换器使用默认 formats并且不可配置(据我所知)。

JsonSerializerSettings jss = new JsonSerializerSettings();
jss.ConfigureForNodaTime(DateTimeZoneProviders.Bcl);

jss.Converters.Remove(NodaConverters.LocalTimeConverter);
jss.Converters.Add(new NodaPatternConverter<LocalTime>(LocalTimePattern.CreateWithInvariantCulture("HH':'mm")));

MyObject mo2 = JsonConvert.DeserializeObject<List<MyObject>>(serializedObject2, jss)[0];

关于c# - 使用 JSON.NET 和 NodaTime 从 JSON 反序列化 LocalTime 导致 NodaTime.Text.UnparsableValueException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37449320/

相关文章:

c# - 面板上的 DrawToBitmap 为空白

PHP日期格式/Date(1365004652303-0500)/

asp.net-mvc-4 - 使用 MVC4 ApiController 时如何清理 JSON 输入参数?

c# - 我在回发方面遇到了一个奇怪的问题,它重定向而不是回发

c# - 从 .tlb 文件创建互操作 dll

c# - 将所有流量转发到 http 代理(隧道)

visual-studio-2010 - 错误 'Newtonsoft.Json.Linq.JToken' 无法使用 TombstoneHelper 序列化

javascript - 使用/jquery 测量 javascript 中大型 json 的下载进度

java - 如何在不知道 Gson key 的情况下解析 JsonObject 列表?

json.net - 没有带有设置和转换器参数的 Json.net 构造函数