代码之家  ›  专栏  ›  技术社区  ›  Bartosz

DataContractJsonSerializer在反序列化期间将字典内的日期时间值字符串化

  •  0
  • Bartosz  · 技术社区  · 7 年前

    不能

    JavaScriptSerializer DataContractJsonSerializer . JavaScriptSerializer没有正常工作,因为它坚持使用一些愚蠢的日期时间格式,这会在反序列化后丢失UTC偏移量,不管怎样。

    我正在为序列化和反序列化指定自定义日期格式(ISO),字符串看起来还可以。此外,Json.NET可以正确读取它。

    我如何有效地解决这个问题, 不做任何正则表达式和手动 转换?

    [Test]
        public void SerializerFailure()
        {
           TestObject testObject = new TestObject() {Dict = new Dictionary<string, object>() {{"DateTest", DateTime.UtcNow}, {"DecimalTest", 66.6M}}};
            Assert.IsInstanceOf<DateTime>(testObject.Dict["DateTest"]);
    
            string serialized = this.Serialize(testObject);
            //output is OK...
    
            //{"Dict":{"DateTest":"2019-01-07T23:16:59.5142225Z","DecimalTest":66.6}}
            TestObject deserialized = this.Deserialize<TestObject>(serialized);
            Assert.IsInstanceOf<string>(deserialized.Dict["DateTest"]);
    
            TestObject newtonDeserialized = JsonConvert.DeserializeObject<TestObject>(serialized);
            testObject.ShouldBeEquivalentTo(newtonDeserialized); //passes OK
    
    
            testObject.ShouldBeEquivalentTo(deserialized); //Fails
    
            //ERROR: Expected member Dict[DateTest] to be 
            //      "2019-01-07T23:27:23.0758967Z" with a length of 28, but
            //      "07.01.2019 23:27:23" has a length of 19.
            //          Expected member Dict[DateTest] to be
            //      "2019-01-07T23:27:23.0758967Z", but
            //      "07.01.2019 23:27:23" differs near "07."(index 0).
    
        }
    

    序列化:

        public string Serialize(object objectToPost)
        {
            using (MemoryStream stream = new System.IO.MemoryStream())
            {
                var settings = new DataContractJsonSerializerSettings() { DateTimeFormat = new DateTimeFormat("O"), UseSimpleDictionaryFormat = true };
    
                DataContractJsonSerializer serializer
                    = new DataContractJsonSerializer(objectToPost.GetType(), settings);
                serializer.WriteObject(stream, objectToPost);
                stream.Flush();
                stream.Seek(0, SeekOrigin.Begin);
                using (StreamReader reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    

        public T Deserialize<T>(string stringContent)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(stringContent)))
                {
                    var settings = new DataContractJsonSerializerSettings() { DateTimeFormat = new DateTimeFormat("O"), UseSimpleDictionaryFormat = true };
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), settings);
                    return (T)serializer.ReadObject(ms);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Error while deserializing string as {typeof(T).Name}", ex);
            }
    
        }
    
    0 回复  |  直到 7 年前