gpt4 book ai didi

javascript - WCF Rest Api 日期时间 JSON 序列化问题

转载 作者:太空宇宙 更新时间:2023-11-04 15:42:09 25 4
gpt4 key购买 nike

当我将 Javascript 日期类型作为参数发送到 WCF 方法时,出现以下序列化问题。 (而他们都使用 JSON)。

DateTime content '2017-05-04T13:09:11.737Z' does not start with '\/Date(' and end with ')\/' as required for JSON.'. 

解决此序列化问题的最佳方法是什么?看起来它可以通过字符串操作来解决,但是对于包含 DateTime 类型的所有 WCF 方法是否有任何通用方法? (客户端或服务器端)

这是测试 Angular Http 帖子

this.http.post(myTestDateUrl, JSON.stringify( {date : new Date()} ) , {headers: this.getHeaders()})
.subscribe(
data => {
console.log(data);
},
error => {
console.log(error);
}
);

private getHeaders() {

let headers = new Headers();
headers.append('Content-Type', 'application/json');
return headers;
}

这是WCF测试方法

[WebInvoke(
Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
[OperationContract]
public Stream TestDate(DateTime date)
{
try
{
dynamic result = new { status = "OK"};
return Send(result);
}
catch (Exception ex)
{
dynamic result = new { status = "ERROR", error = ex.Message };
return Send(result);
}
}

最佳答案

我建议根据 this 使用 ISO 8601 格式:

There is no right format; The JSON specification does not specify a format for exchanging dates which is why there are so many different

ways to do it.

The best format is arguably a date represented in 8601 format; it is a well known and widely used format and can be handled across many

different languages, making it very well suited for interoperability. If you have control over the generated json, for example, you provide data to other systems in json format, choosing 8601 as the date interchange format is a good choice.

所以你可以创建这样的东西:

    public Stream TestDate(string date)
{
try
{
DateTime d;
DateTime.TryParseExact(date, @"yyyy-MM-dd\THH:mm:ss\Z", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out d);
dynamic result = new { status = "OK" };
return Send(result);
}
catch (Exception ex)
{
dynamic result = new { status = "ERROR", error = ex.Message };
return Send(result);
}
}

关于javascript - WCF Rest Api 日期时间 JSON 序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43788185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com