Newtonsoft.Json试图猜测令牌类型并弄错了

时间:2017-08-02 12:19:00

标签: c# json.net

我正在尝试更改Newtonsoft序列化程序处理“2017-05-27”等字符串的方式。

所以,我创建了一个类来代替DateTime,这个类型的转换器,希望它就是它。

问题是,对于“2017-05-27”它的确有效。但是,如果由于某种原因,我得到“2017-05-27T23:50:27:00”,即完整的ISO 8601字符串,JsonReader假装是智能的,并将其视为DateTime而不是字符串。

有没有办法改变这种行为?

到目前为止,我所做的代码是:

using System;
using System.Text.RegularExpressions;
using Newtonsoft.Json;

namespace ConverterGames
{
    public class MyDate
    {
        public int Year { get; set; }
        public int Month { get; set; }
        public int Day { get; set; }
    }
    public class Xxx
    {
        public MyDate Aaa { get; set; }
    }

    public class DateJsonConverter : JsonConverter
    {
        private readonly Regex _isoDate = new Regex(@"^(\d+)-(\d+)-(\d+).*", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // gives "string" for 2017-04-27 :-)
            // gives DateTime for 2017-04-27T20:00:00.00 :-(
            // I want string only here.
            Console.WriteLine(reader.Value.GetType());

            Match m = _isoDate.Match((string)reader.Value);
            if (!m.Success)
            {
                throw new Exception($"Format error for {(string)reader.Value}");
            }
            return new MyDate
            {
                Year = Int32.Parse(m.Groups[1].Value),
                Month = Int32.Parse(m.Groups[2].Value),
                Day = Int32.Parse(m.Groups[3].Value),
            };
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(MyDate);
        }
    }

    class Program
    {
        static void Main()
        {
            string Data = "{\"aaa\":\"2017-05-12\"}";
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.Converters.Add(new DateJsonConverter());

            // good
            Xxx x= JsonConvert.DeserializeObject<Xxx>(Data, settings);
            Console.WriteLine(x.Aaa.Year);


            // fails
            Data = "{\"aaa\":\"2017-05-12T08:15:00\"}";
            x = JsonConvert.DeserializeObject<Xxx>(Data, settings);
            Console.WriteLine(x.Aaa.Year);
        }
    }
}

我能做些什么吗?

1 个答案:

答案 0 :(得分:4)

是。由于您将自己处理日期解析,因此您只需在序列化设置中将DateParseHandling设置为None

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.DateParseHandling = DateParseHandling.None;
settings.Converters.Add(new DateJsonConverter());

小提琴:https://dotnetfiddle.net/3WSj6Q