2015-01-13 57 views
3

使用日期時間轉換器時,我遇到了解析下面的JSON的麻煩。我理解「 - 」和「at」會導致問題,但這是我在響應中的JSON,並且無法控制它。使用JSON.NET實現自定義日期時間轉換器

"[{\"Desc\":\"Unacceptable Signal\",\"Station\":\"Test\",\"When\":\"Tuesday - 5/18/10 at 3:34 PM\"},{\"Desc\":\"Low Battery\",\"Station\":\"Test Unit (21261)\",\"When\":\"Wednesday - 3/30/11 at 12:34 AM\"}]" 

我的型號是:

public class CurrentAlarms 
    { 
     public string Desc { get; set; } 
     public string Station { get; set; } 
     public DateTime When { get; set; } 

     public CurrentAlarms() { } 

     public CurrentAlarms(string desc, string station, DateTime when) 
     { 
      Desc = desc; 
      Station = station; 
      When = when; 
     } 
    } 

我試圖反序列化,如下所示,甚至通過刪除「在」的日期時間字符串,但我仍然得到「字符串不是正確的格式「來自JSON.NET的異常。我很難找出其他解決方法。任何幫助,將不勝感激!在ReadJson

json = json.Replace(" at ", " "); 

var format = "dddd MM/dd/yy h:mm tt"; 
var dateTimeConverter = new IsoDateTimeConverter {DateTimeFormat = format}; 

var result = JsonConvert.DeserializeObject<ObservableCollection<CurrentAlarms>>(json, dateTimeConverter); 
+0

你還有一個' - '不是嗎? (「Wednesday - 3/30/11 12:34 AM」) –

+0

同意@JonSkeet - 您的問題並不表示您嘗試刪除' - '字符,並且您的轉換器不顯示它。 – theMayer

+0

啊,是的,我很抱歉。我試圖刪除' - '字符,但得到相同的結果。 – YnotDraw

回答

9
public class CurrentAlarms 
{ 
    public string Desc { get; set; } 
    public string Station { get; set; } 
    [JsonConverter(typeof(InvalidDataFormatJsonConverter))] 
    public DateTime When { get; set; } 

    public CurrentAlarms() { } 

    public CurrentAlarms(string desc, string station, DateTime when) 
    { 
     Desc = desc; 
     Station = station; 
     When = when; 
    } 
} 

class InvalidDataFormatJsonConverter : JsonConverter 
{ 
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
    { 
     // implement in case you're serializing it back 
    } 

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, 
     JsonSerializer serializer) 
    { 
     var dataString = (string) reader.Value; 
     DateTime date = parseDataString;    

     return date; 
    } 

    public override bool CanConvert(Type objectType) 
    { 
     return true; 
    } 
} 

嘗試調試和解析日期還有 - 它應該是更容易了。

+0

@YnotDraw如果你接受 - 你也可以調高;) – fex

相關問題