我正在尝试更改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);
        }
    }
}


有什么我可以做的吗?

最佳答案

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

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


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

关于c# - Newtonsoft.Json尝试猜测 token 类型并弄错了它,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45460708/

10-14 16:47