允许在 JsonServiceClient 中将日期反序列化为 js Date 对象

allow for deserializing dates as js Date object in JsonServiceClient

肯定与其他问题相关(例如 ),但我想我问得更多 =)

首先,我确实理解 json 没有传递真正的 JS 日期,这是 ServiceStack 将 C# DTO DateTime 代码生成为 TypeScript 中的字符串的原因...

然而在其他获取客户端包装器中,类似于 SS JsonServiceClient,我有很好的经验使用 JSON.parse(json, reviver) 的第二个参数来查找日期模式并反序列化为正确的 JS 日期...

切入正题,作为概念证明,我已经修改了“JsonServiceClient.prototype.createResponse = function (res, request)”,就像这样...

...
    if (isJson) {
        // return res.json().then(function (o) {
        //     return o;
        // });
        return res.text().then(function (o) {
            return JSON.parse(o, 
                (_key, value) => (typeof value === 'string' && value.startsWith('/Date')) ? new Date(parseFloat(value.slice(6,-2))) : value
            );
        });
    }
...

对于其他人来说,已经有了 TypeScriptGenerator 钩子来影响我想要的代码生成器是非常好的,例如

TypeScriptGenerator.PropertyTypeFilter = (gen, type, prop) =>
    (prop.Type == "DateTime" ? "Date" : gen.GetPropertyType(prop, out var isNullable));

对于背景,向强大的 React DataGrid 提供适当的日期变得非常优雅(我碰巧使用 Telerik/Progress“KendoRect”套件)...当存在真实日期时,网格的本机行为可以对这些日期进行过滤和排序,而不是使用字符串。

神话,

您能否考虑为 JsonServiceClient 提供一个“钩子”,以便我们可以提供这样的自定义反序列化函数?或可能的替代方案?

感谢您所做的一切!

仅供参考,我使用的是最新的 v5.9.3 堆栈

我在 this commit 中的 JsonServiceClient 上添加了一个 parseJson 挂钩,您可以在其中自定义 JSON 在 JsonServiceClient 中的解析方式:

const client = new JsonServiceClient(baseUrl);
client.parseJson = res => res.text().then(s => JSON.parse(s,reviver));

此更改适用于现在位于 npm 上的 v1.0.34+。