Deserialize Json Object - DateTime

前端 未结 5 2026
说谎
说谎 2020-12-10 18:37

My web-api returns an User Object. In that object there is a DateTime property. When i\'am reading it in my Application i get an error because the

5条回答
  •  暖寄归人
    2020-12-10 18:48

    Just change the DateTimeFormat on your DataContractJsonSerializer like so:

        public static T Deserialize(string json) {
        try
        {
            var settings = new DataContractJsonSerializerSettings 
            {
                DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("o")
            };
            var _Bytes = Encoding.Unicode.GetBytes(json);
            using (MemoryStream _Stream = new MemoryStream(_Bytes))
            {
    
                var _Serializer = new DataContractJsonSerializer(typeof(T), settings);
    
                return (T)_Serializer.ReadObject(_Stream);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    

提交回复
热议问题