反序列化JSON的最佳方法是什么
我有以下JSON
"_created" : {
"$dt": "2013-03-26T16:45:20Z"
}
和我想得到对象的字段,像这样- DataTime Created {get; set;}
json.net http://james.newtonking.com/projects/json-net.aspx专家提问
最简单的方法是创建jsonconverter
public class MongoDbDateTimeConverter : DateTimeConverterBase
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jObject = JObject.Load(reader);
return jObject["$dt"].Value<DateTime>();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
并与属性
一起使用[JsonConverter(typeof(MongoDbDateTimeConverter))]
public DateTime Created { get; set; }
你可以使用NewtonSoft的JSON序列化器/反序列化器,对我来说工作得很好。
Nuget包
MediaTypeFormatter例子
将以下MediaTypeFormatter添加到GlobalConfiguration中,如下所示:
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonFormatter());
MediaTypeFormatter:
public class JsonFormatter : MediaTypeFormatter
{
private const string WesternEuropeStandardTime = "W. Europe Standard Time";
private TimeZoneInfo timeZoneInfo;
public JsonFormatter()
{
SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
this.timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(WesternEuropeStandardTime);
}
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return true;
}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
{
Task<object> task = Task<object>.Factory.StartNew(() =>
{
JsonSerializerSettings settings = new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
};
StreamReader sr = new StreamReader(readStream);
JsonTextReader jreader = new JsonTextReader(sr);
JsonSerializer ser = new JsonSerializer();
ser.Converters.Add(new DateTimeConverter(this.timeZoneInfo) { DateTimeFormat = "o" });
return ser.Deserialize(jreader, type);
});
return task;
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
{
Task task = Task.Factory.StartNew(() =>
{
JsonSerializerSettings settings = new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
};
string json = JsonConvert.SerializeObject(
value,
Formatting.Indented,
new JsonConverter[1] { new DateTimeConverter(this.timeZoneInfo) { DateTimeFormat = "o" } });
byte[] buf = System.Text.Encoding.Default.GetBytes(json);
writeStream.Write(buf, 0, buf.Length);
writeStream.Flush();
});
return task;
}
private class DateTimeConverter : IsoDateTimeConverter
{
private TimeZoneInfo timeZoneInfo;
public DateTimeConverter(TimeZoneInfo timeZoneInfo)
{
this.timeZoneInfo = timeZoneInfo;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
DateTime? date = value as DateTime?;
if (date.HasValue && DateTime.MinValue != date.Value && DateTime.MaxValue != date.Value)
{
TimeSpan timeZoneOffset = this.timeZoneInfo.GetUtcOffset(date.Value);
value = DateTime.SpecifyKind(date.Value - timeZoneOffset, DateTimeKind.Utc);
}
base.WriteJson(writer, value, serializer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object result = base.ReadJson(reader, objectType, existingValue, serializer);
DateTime? date = result as DateTime?;
if (date.HasValue && DateTime.MinValue != date.Value && DateTime.MaxValue != date.Value)
{
TimeSpan timeZoneOffset = this.timeZoneInfo.GetUtcOffset(date.Value);
result = DateTime.SpecifyKind(date.Value + timeZoneOffset, DateTimeKind.Utc);
}
return result;
}
}
}
如果您使用json.NET
尝试serialize
一个datetime
字段或object
组成的datetime
字段,像这样:
JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};
string serializedObject= Newtonsoft.Json
.JsonConvert
.SerializeObject(data, microsoftDateFormatSettings);
如果使用JSON.NET
完成序列化,它可以正常工作:)
然后你就可以成功反序列化它了
var myobject = Newtonsoft.Json.JsonConvert.DeserializeObject(serializedObject);
如果你问的是c#中的JSON解析器,那么这更多的是谷歌的事情。去那里找找看。有很多可用的
如果您正在询问如何将此字符串解析为DateTime,那么DateTime.TryParse()
将帮助您。您可以通过提供字符串格式来帮助它,例如yyyy-MM-ddTHH:mm:ss
。