欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ServiceStack DateTime数据类型转Json出现的困扰

程序员文章站 2022-07-02 16:46:01
执行dotnet-new selfhost sstest 创建项目,然后打开解决方案 修改ssTest.ServiceModel中的Hello.cs,在HellopResponse中添加时间属性,然后修改MyServices中的代码 运行程序,打开Postman查看返回结果 可以看到Json中dat ......

执行dotnet-new selfhost sstest 创建项目,然后打开解决方案

ServiceStack DateTime数据类型转Json出现的困扰

修改sstest.servicemodel中的hello.cs,在hellopresponse中添加时间属性,然后修改myservices中的代码

ServiceStack DateTime数据类型转Json出现的困扰

运行程序,打开postman查看返回结果

 ServiceStack DateTime数据类型转Json出现的困扰

 

 可以看到json中date属性返回的是  "date": "/date(1555810731732+0800)/",直接导致前段js无法识别该字段,该如何解决?

在startup中加入以下代码,任何时间都转换为iso8601字符串

    public class startup
    {
        // this method gets called by the runtime. use this method to add services to the container.
        public void configureservices(iservicecollection services)
        {
        }

        // this method gets called by the runtime. use this method to configure the http request pipeline.
        public void configure(iapplicationbuilder app, ihostingenvironment env)
        {
            jsconfig<datetime>.serializefn = time => new datetime(time.ticks, datetimekind.local).tostring("o");
            jsconfig<datetime?>.serializefn =
                time => time != null ? new datetime(time.value.ticks, datetimekind.local).tostring("o") : null;
            jsconfig.datehandler = datehandler.iso8601;

            app.useservicestack(new apphost());

            app.run(context =>
            {
                context.response.redirect("/metadata");
                return task.fromresult(0);
            });
        }
    }

 

打开postman再次运行,查看结果

ServiceStack DateTime数据类型转Json出现的困扰

 

前段js再次取得该字符串时间,就可以正确的识别时间类型字段了。