2016-05-25 72 views
4

我有一個問題反序列化時間值到LocalTime-授予,我很新的NodaTime。我想導入一個以「HH:mm」格式列出時間的Web服務結果。除非我使用「hh:mm:ss.fff」格式的時間,否則我會得到例外。有沒有辦法指定不同的模式,並獲得「HH:mm」的工作?從JSON反序列化LocalTime使用JSON.NET和NodaTime結果NodaTime.Text.UnparsableValueException

請參閱此代碼

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: 
+0

所有版本都是「最新」的穩定版本。 –

回答

6

你需要刪除默認的轉換器在調用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]; 
+1

我不得不添加一個:「使用NodaTime.Text」。否則,完美。謝謝! –

+0

@DavidRogers由於代碼中的*輕微*差異,我已經回滾了編輯。從[documentation](http://nodatime.org/1.2.x/userguide/text.html) - * Where valid,:始終指文化特定的時間分隔符(不變文化中的冒號)* - 此意味着在':'注*時間分隔符的本地運行代碼時,它將無法解析。指定'':''表示我們正在查找冒號,而不考慮語言環境。 – Rob

+0

它也保持與默認模式的一致性:https://github.com/nodatime/nodatime/blob/69a2cdad9cb4c32a82620eae4f2460ff9479570a/src/NodaTime/Text/LocalDateTimePattern.cs#L76 – Rob