datetime json 序列化时丢掉时区

论坛 期权论坛 脚本     
匿名技术用户   2020-12-27 12:22   11   0

asp.net mvc web api test client 是个好东西,能够直接测试api调用。

但有一点是,生成datetime类型的测试数据时,是带有时区的,导致在调用的时候,反序列化失败。不得不手动修改一下时间的格式。

如下图:


那我们就手动修改一下代码,使其序列化时放弃时区吧

代码修改对比:


位置:

file: $\Areas\HelpPage\SampleGeneration\HelpPageSampleGenerator.cs

class: HelpPageSampleGenerator

Method: private static string TryFormatJson(string str)

LN: 380

        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
        private static string TryFormatJson(string str)
        {
            try
            {
                object parsedJson = JsonConvert.DeserializeObject(str);
                Newtonsoft.Json.Converters.IsoDateTimeConverter timeFormat = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
                timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";

                return JsonConvert.SerializeObject(parsedJson, Formatting.Indented, timeFormat);
            }
            catch
            {
                // can't parse JSON, return the original string
                return str;
            }
        }

修改以后生成的示例:




分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP