datetime字段的反序列化问题

时间:2013-03-27 09:31:06

标签: c# json.net deserialization

反序列化JSON的最佳方法是什么

我有以下JSON

"_created" : { 
                "$dt": "2013-03-26T16:45:20Z" 
             }

我希望获得对象的字段,像这样 - DataTime Created {get; set;}

json.net http://james.newtonking.com/projects/json-net.aspx专家的问题

4 个答案:

答案 0 :(得分:1)

最简单的方法是创建JsonConvertor

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; }

答案 1 :(得分:0)

您可以使用NewtonSoft中的JSON序列化程序/反序列化程序,对我来说没问题。

Nuget

MediaTypeFormatter example

将以下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;
        }
    }
}

答案 2 :(得分:0)

如果您使用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);

答案 3 :(得分:-1)

如果您在C#中询问JSON解析器,那么这更像是Google的事情。去搜索那里。有很多可用的。

如果您询问如何将此字符串解析为DateTime,那么DateTime.TryParse()将对您有所帮助。您可以通过提供的字符串格式来帮助它,例如yyyy-MM-ddTHH:mm:ss