我从API中获取数据,如下所示:
{
created_utc: 1442108087,
body: "test"
}
这是我用于反序列化的强类型类:
public class Comment
{
[JsonProperty("created_utc")]
public DateTime CreatedUtc { get; set; }
[JsonProperty("body")]
public string Body { get; set; }
}
如何使用Json.Net解析这个created_utc
属性,这个属性是JS编号格式,以C#格式表示为UTC时的日期时间?
答案 0 :(得分:2)
你可以试试这个
[JsonProperty("created_utc")]
[JsonConverter(typeof(UTCDateTimeConverter))]
public DateTime CreatedUtc { get; set; }
public class UTCDateTimeConverter : JsonConverter
{
public override object ReadJson(
JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
long ts = serializer.Deserialize<long>(reader);
return TimeUtils.GetMbtaDateTime(ts);
}
public override bool CanConvert(Type type)
{
return typeof(DateTime).IsAssignableFrom(type);
}
public override void WriteJson(
JsonWriter writer,
object value,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanRead
{
get { return true; }
}
}
对我来说可能更容易的另一种方法
[JsonProperty(ItemConverterType = typeof(UTCDateTimeConverter))]
public DateTime CreatedUtc { get; set; }
var AllComments = JsonConvert.DeserializeObject<Comment>(json, new UTCDateTimeConverter());
public class UTCDateTimeConverter : Newtonsoft.Json.JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds((long)reader.Value);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}