在大型json数据响应中使用来自$http.get的AngularJS格式化日期
我正在Angular控制器中成功调用$http.get并返回一个大型json对象。像这样:在大型json数据响应中使用来自$http.get的AngularJS格式化日期,angularjs,json,Angularjs,Json,我正在Angular控制器中成功调用$http.get并返回一个大型json对象。像这样: var self=this; self.createNewStatusReport = function() { $http.get(self.NewStatusReportUrl).then(function(response) { self.AngularModel.StatusReportJsons.push(response.data); }); }; 返
var self=this;
self.createNewStatusReport = function()
{
$http.get(self.NewStatusReportUrl).then(function(response)
{
self.AngularModel.StatusReportJsons.push(response.data);
});
};
返回的json包含许多日期。不幸的是,格式如下:/Date(1420099200000)/。下面是一段简化的响应数据:
{
"StatusReportID": 25,
"DueDate": "/Date(1468566000000)/",
"SubmitDate": null,
"WorkStatement": [
{
"WorkStatementID": 41,
"Milestone": [
{
"MilestoneID": 501,
"ContractorComments": null,
"Title": "Do some specific piece of work",
"StartDate": "/Date(1459494000000)/",
"EndDate": "/Date(1469948400000)/",
"IsCompleted": false,
...
我还可以(部分)控制服务器端,但无法从DateTime更改StatusReportJson中的日期类型?串。它是用C#编写的MVC:
有没有一种简单的方法可以递归地将这些日期字符串转换为日期对象?我收到的响应数据已经被解析;我可以插入自己的解析步骤吗?在服务器端,我是否可以在不修改StatusReportJson对象数据类型的情况下,将日期作为更像“2016-04-01T00:00:00”或简单的“2016-04-01”的日期字符串输入?其他人已经在这里解决了转换问题:我需要帮助构建解决方案的位置,以便在我的案例中有效。谢谢你的帮助 希望这能解决您的问题:
$scope.DateIssue = function(input) {
input = '/Date(1468566000000)/';
$scope.formatedDate = input.toString().replace('/Date(', '').replace(')/', '');
$scope.formatedDate = $filter('date', $scope.formatedDate);
return $scope.formatedDate
}) 下面是我如何解决这个问题的。首先,我在服务器端使用JavaScript序列化程序,如下所示:
[HttpGet]
public JsonResult NewStatusReport(string agreementNumber)
{
var statusReport = StatusReports.GetStatusReport(25);
var statusReportJson = new StatusReportJson(statusReport);
var json = new JavaScriptSerializer().Serialize(statusReportJson);
return Json(json, JsonRequestBehavior.AllowGet);
}
var self = this;
$http.get(self.NewStatusReportUrl).then(function(response)
{
var jsonObject = jQuery.parseJSON(response.data, true);
self.AngularModel.StatusReportJsons.push(jsonObject);
});
然后,在客户端,我从这个优秀的页面中提取代码,并这样调用它:
[HttpGet]
public JsonResult NewStatusReport(string agreementNumber)
{
var statusReport = StatusReports.GetStatusReport(25);
var statusReportJson = new StatusReportJson(statusReport);
var json = new JavaScriptSerializer().Serialize(statusReportJson);
return Json(json, JsonRequestBehavior.AllowGet);
}
var self = this;
$http.get(self.NewStatusReportUrl).then(function(response)
{
var jsonObject = jQuery.parseJSON(response.data, true);
self.AngularModel.StatusReportJsons.push(jsonObject);
});
感谢Robert Koritnik的回答!感谢所有帮助过我的人 有点晚了,但我觉得有帮助。 大多数建议是在当地进行转换。在我的例子中,日期作为字符串返回(带有时区信息) 例如“2018-06-01T13:57:41.3867449Z” 因此,我为getJson和PostJson创建了一个公共服务,并在其中使用“$q”处理响应
if (response.data) {
// Check for datetime object & convert
// TODO:: *** May impact performance, so check later or use momentJS
//console.info('Before-convertDateStringsToDates:', new Date());
appUtils.convertDateStringsToDates(response.data);
//console.info('After-convertDateStringsToDates:', new Date());
}
我的appUtil方法如下所示:
// --------------------------------------------------------------------------------
// Ref: http://aboutcode.net/2013/07/27/json-date-parsing-angularjs.html
// Function to convert string (as ReGex format) property to date - used as generic in Common Serivce.
convertDateStringsToDates(input) {
// ReGex for format we receive from Web API e.g. "1980-05-09T00:00:00Z"
var jsonDateTimeFormatRegex = "((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))";
// Ignore things that aren't objects.
if (typeof input !== "object") return input;
for (var key in input) {
if (!input.hasOwnProperty(key)) continue;
var value = input[key];
var match;
// Check for string properties which look like dates.
// TODO: Improve this regex to better match ISO 8601 date strings.
if (typeof value === "string" && (match = value.match(jsonDateTimeFormatRegex))) {
// Assume that Date.parse can parse ISO 8601 strings, or has been shimmed in older browsers to do so.
//console.info(match[0]);
var date = new Date(match[0]); // Need to convert to UTC. Ref: https://stackoverflow.com/a/14006555/1161069
input[key] = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
// var milliseconds = Date.parse(match[0]);
// if (!isNaN(milliseconds)) {
// input[key] = new Date(milliseconds);
// }
} else if (typeof value === "object") {
// Recurse into object
this.convertDateStringsToDates(value);
}
}
}
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
//var cors = new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
// other code ......
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
//jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
JsonSerializerSettings jSettings = new JsonSerializerSettings()
{
Formatting = Formatting.None
};
jSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
jsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
jsonFormatter.SerializerSettings = jSettings;
// rest of the code....
}
现在,在每次GET或POST请求之后,我都会得到带有正确日期的JSON
如果有人想知道Web API代码,请参见以下内容:
// --------------------------------------------------------------------------------
// Ref: http://aboutcode.net/2013/07/27/json-date-parsing-angularjs.html
// Function to convert string (as ReGex format) property to date - used as generic in Common Serivce.
convertDateStringsToDates(input) {
// ReGex for format we receive from Web API e.g. "1980-05-09T00:00:00Z"
var jsonDateTimeFormatRegex = "((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))";
// Ignore things that aren't objects.
if (typeof input !== "object") return input;
for (var key in input) {
if (!input.hasOwnProperty(key)) continue;
var value = input[key];
var match;
// Check for string properties which look like dates.
// TODO: Improve this regex to better match ISO 8601 date strings.
if (typeof value === "string" && (match = value.match(jsonDateTimeFormatRegex))) {
// Assume that Date.parse can parse ISO 8601 strings, or has been shimmed in older browsers to do so.
//console.info(match[0]);
var date = new Date(match[0]); // Need to convert to UTC. Ref: https://stackoverflow.com/a/14006555/1161069
input[key] = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
// var milliseconds = Date.parse(match[0]);
// if (!isNaN(milliseconds)) {
// input[key] = new Date(milliseconds);
// }
} else if (typeof value === "object") {
// Recurse into object
this.convertDateStringsToDates(value);
}
}
}
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
//var cors = new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
// other code ......
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
//jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
JsonSerializerSettings jSettings = new JsonSerializerSettings()
{
Formatting = Formatting.None
};
jSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
jsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
jsonFormatter.SerializerSettings = jSettings;
// rest of the code....
}
公共静态无效寄存器(HttpConfiguration配置)
{
//Web API配置和服务
//var cors=new System.Web.Http.cors.EnableCorsAttribute(“*”、“*”、“*”);
配置使能cors(cors);
//Web API路由
config.maphttpAttribute路由();
//其他代码。。。。。。
var jsonFormatter=config.Formatters.OfType().First();
//jsonFormatter.SerializerSettings.ContractResolver=新的CamelCasePropertyNamesContractResolver();
JsonSerializerSettings jSettings=新的JsonSerializerSettings()
{
格式化=格式化。无
};
jSettings.ContractResolver=新的CamelCasePropertyNamesContractResolver();
jsonFormatter.SerializerSettings.DateTimeZoneHandling=DateTimeZoneHandling.Local;
jsonFormatter.SerializerSettings=jSettings;
//代码的其余部分。。。。
}
在推送到数组之前,简单地循环数据并转换每个实例。必须进行客户端数据转换并不是一件不寻常的事情,这会产生一种我不希望有的依赖关系。如果StatusReportJson在服务器端发生更改(这很可能发生),我不希望必须更改客户端以匹配。使代码不易维护。我不知道如何在服务器端进行更改。但在客户端,您可以使用一个过滤器,将/Date()/字符串转换为一个数字,然后将该数字传递给标准的日期过滤器。。。没道理,有意思。你说的是角滤波器吗?(我还不太熟悉它们。)假设我可以查看如何编写一个,那么在解析json之前,我将如何将它放在适当的位置以在这里工作?谢谢。嗯,但我有一个对象,不是字符串。有没有办法在angular进行json反序列化之前运行预处理响应的函数?您可以将该对象转换为字符串并使用此函数。