0

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

我有以下 JSON

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

我想得到对象的领域,像这样 -DataTime Created {get; set;}

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

4

4 回答 4

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; }
于 2013-03-28T08:57:32.127 回答
0

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

Nuget

MediaTypeFormatter 示例

将以下 MediaTypeFormatter 添加到 GlobalConfiguration 中,如下所示:

GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonFormatter());

媒体类型格式化程序:

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;
        }
    }
}
于 2013-03-27T09:43:15.687 回答
0

如果你正在使用json.NET

尝试这样serializedatetime字段或由字段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);
于 2013-03-27T10:03:38.467 回答
-1

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

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

于 2013-03-27T09:34:26.887 回答