使用
日期时间转换器时,我在解析以下 JSON 时遇到问题。 我知道"-"和"at"会导致问题,但这是我在响应中的 JSON,无法控制它。
"[{"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;
}
}
我已经尝试反序列化它,如下所示,即使删除日期时间字符串中的"at",但我仍然从 JSON.NET 中得到"字符串格式不正确"异常。我很难找到其他解决方法。 任何帮助将不胜感激!
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);
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;
}
}
尝试在 ReadJson 上调试它并在那里解析日期 - 现在应该更容易了。