【问题标题】:ServiceStack CSV serializer putting extra quotes around serialized dateServiceStack CSV 序列化程序在序列化日期周围加上额外的引号
【发布时间】:2015-06-24 22:32:00
【问题描述】:

我在我的站点中使用 ServiceStack 来允许用户下载系统数据集之一的 csv。在我的 AppHost 的配置方法中,我为 DateTime 提供了一个自定义序列化程序。看起来是这样的

JsConfig<DateTime>.SerializeFn = time =>
  {
      var result = time;
      if (time.Kind == DateTimeKind.Unspecified)
      {
          result = DateTime.SpecifyKind(result, DateTimeKind.Local);
      }
          return result.ToString(CultureInfo.InvariantCulture);
  };

当使用 csv 格式时,结果中的所有日期都用额外的引号括起来;例如结果是 """06/24/2015 16:22:16""" 而我希望它是 "06/24/2015 16:22:16"

在我看来,这一定是 ServiceStack 序列化中的错误。有没有办法防止这种情况发生?下面是一个完整的例子,展示了向 /csv/oneway/Request 发出请求时出现的问题

public class AppHost : AppHostBase
{
    /// <summary>
    /// Default constructor.
    /// Base constructor requires a name and assembly to locate web service classes. 
    /// </summary>
    public AppHost()
        : base("CSVBug", typeof(MyService).Assembly)
    {

    }

    public override void Configure(Container container)
    {
        JsConfig<DateTime>.SerializeFn = time =>
        {
            var result = time;
            if (time.Kind == DateTimeKind.Unspecified)
            {
                result = DateTime.SpecifyKind(result, DateTimeKind.Local);
            }
            return result.ToString(CultureInfo.InvariantCulture);
        };
    }
}

public class Request
{

}

public class Response
{
    public DateTime DateTime { get; set; }
}

public class MyService : Service
{
    public object Any(Request reuqest)
    {
        return new Response()
        {
            DateTime = DateTime.Now
        };
    }
}

和 Global.asax.cs

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        new AppHost().Init();
    }
}

【问题讨论】:

    标签: csv servicestack servicestack-text


    【解决方案1】:

    现在应该解决 with this commit 问题,从 v4.0.41+ 开始可用,现在是 available on MyGet

    【讨论】:

    • 谢谢@mythz,这给了我想要的结果。我仍然很困惑为什么从我的原始函数返回的字符串值从 06/24/2015 16:22:16 变为 """06/24/2015 16:22:16"""。我可以理解用引号保护该值,例如“2015 年 6 月 24 日 16:22:16”,但似乎在某处被转义,然后再次被引用。是否有关于 SerialFn 调用和通过网络发送的内容之间发生了什么的文档?
    • 其实这对我不起作用。我以 CSV 格式获得了所需的结果,但随后我的 JSON 客户端中断了。例如,在 csv 中我得到 DateTime 06/25/2015 14:44:41 但使用 json 我得到 {"DateTime":06/25/2015 14:45:05} 这是无法解析的。
    • 更新成功了。以 csv 和 JSON 格式获得所需的结果。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多