2017-06-28 79 views
0

我正在ASP.NET MVC 5中工作。 我试图从JSON格式的服务器反序列化日期。 JSON到了,当我试图反序列化调试器刚停止的日期,并且不显示其他控制台中的任何错误时,我都无法理解。 这是我到目前为止的代码:

$(document).ready(function() { 

$.ajax({ 
    type: 'GET', 
    url: '/Home/GetDates', 
    dataType: "json", 
    contentType: "application/json; charset=utf-8", 
    success: function (dates) {   
     var date = dates[0]; 
     var desDate = $.parseJSON(date, true); 
     console.log(desDate); 
    } 

}); 

}); 

下面是对的ErrorMessage和索姆图片一在datat未来

enter image description here

enter image description here

这里是给一个链接我一直在看的文档。 Docs

+0

想要输出是什么样子? –

+0

JSON **已被解析**!这就是将'dataType'设置为'json',它会为你解析它。再次解析它将始终引发错误。 – adeneo

+0

类似于:2014/06/06。我知道也许我不得不通过更多的格式日期,但截至目前我不能让它通过JSON - > JS – AllramEst

回答

2

数据从AJAX调用返回已解析的,所以dates是包含字符串的数组,并dates[0]是字符串/Date(14984....)/

为了解析串,除去除数字外的所有内容,并使用该时间戳创建Date对象。

$(document).ready(function() { 
    $.ajax({ 
     type  : 'GET', 
     url   : '/Home/GetDates', 
     dataType : "json", 
     contentType : "application/json; charset=utf-8", 
     success: function (dates) {   
      var d = dates[0]; 
      var unix = +d.replace(/\D/g, ''); 
      var date = new Date(unix); 

      var desDate = date.getFullYear() + '/' + 
          (date.getMonth()+1) + '/' + 
          date.getDate(); 

      console.log(desDate); 
     } 
    }); 
}); 
+0

这就是我想要的。谢谢您的回答! – AllramEst

1

您需要执行JavaScript的字符串变量内侧,

var dateVar = eval(dates[0]); 

这会给你的日期,但不是你想有一个正确的格式。对于正确的格式用户无论是moment.js或简单地创建你自己的代码行像

var finalDate = new Date(dateVar).toISOString().split('T')[0]; 
console.log(finalDate); 

new Date()这里再次需要,使我们可以利用toISOString(),并得到适当的日期格式。

+0

谢谢。会尽快查找它。在运行。马上。 – AllramEst

1

因为你指的是这个你需要包含在那里定义的jQuery扩展。

的确,在jQuery中,parseJSON(jsonString)在您使用扩展名时只接受一个参数。

此外,您的日期变量是一个字符串数组,而不是一个json字符串。

// 
 
// Look at the end.... 
 
// 
 

 
/* 
 
* jQuery.parseJSON() extension (supports ISO & Asp.net date conversion) 
 
* 
 
* Version 1.0 (13 Jan 2011) 
 
* 
 
* Copyright (c) 2011 Robert Koritnik 
 
* Licensed under the terms of the MIT license 
 
* http://www.opensource.org/licenses/mit-license.php 
 
*/ 
 
(function ($) { 
 

 
    // JSON RegExp 
 
    var rvalidchars = /^[\],:{}\s]*$/; 
 
    var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g; 
 
    var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; 
 
    var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g; 
 
    var dateISO = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.,]\d+)?Z/i; 
 
    var dateNet = /\/Date\((\d+)(?:-\d+)?\)\//i; 
 

 
    // replacer RegExp 
 
    var replaceISO = /"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?Z"/i; 
 
    var replaceNet = /"\\\/Date\((\d+)(?:-\d+)?\)\\\/"/i; 
 

 
    // determine JSON native support 
 
    var nativeJSON = (window.JSON && window.JSON.parse) ? true : false; 
 
    var extendedJSON = nativeJSON && window.JSON.parse('{"x":9}', function (k, v) { 
 
       return "Y"; 
 
      }) === "Y"; 
 

 
    var jsonDateConverter = function (key, value) { 
 
     if (typeof(value) === "string") { 
 
      if (dateISO.test(value)) { 
 
       return new Date(value); 
 
      } 
 
      if (dateNet.test(value)) { 
 
       return new Date(parseInt(dateNet.exec(value)[1], 10)); 
 
      } 
 
     } 
 
     return value; 
 
    }; 
 

 
    $.extend({ 
 
     parseJSON: function (data, convertDates) { 
 
      /// <summary>Takes a well-formed JSON string and returns the resulting JavaScript object.</summary> 
 
      /// <param name="data" type="String">The JSON string to parse.</param> 
 
      /// <param name="convertDates" optional="true" type="Boolean">Set to true when you want ISO/Asp.net dates to be auto-converted to dates.</param> 
 

 
      if (typeof data !== "string" || !data) { 
 
       return null; 
 
      } 
 

 
      // Make sure leading/trailing whitespace is removed (IE can't handle it) 
 
      data = $.trim(data); 
 

 
      // Make sure the incoming data is actual JSON 
 
      // Logic borrowed from http://json.org/json2.js 
 
      if (rvalidchars.test(data 
 
          .replace(rvalidescape, "@") 
 
          .replace(rvalidtokens, "]") 
 
          .replace(rvalidbraces, ""))) { 
 
       // Try to use the native JSON parser 
 
       if (extendedJSON || (nativeJSON && convertDates !== true)) { 
 
        return window.JSON.parse(data, convertDates === true ? jsonDateConverter : undefined); 
 
       } 
 
       else { 
 
        data = convertDates === true ? 
 
          data.replace(replaceISO, "new Date(parseInt('$1',10),parseInt('$2',10)-1,parseInt('$3',10),parseInt('$4',10),parseInt('$5',10),parseInt('$6',10),(function(s){return parseInt(s,10)||0;})('$7'))") 
 
            .replace(replaceNet, "new Date($1)") : 
 
          data; 
 
        return (new Function("return " + data))(); 
 
       } 
 
      } else { 
 
       $.error("Invalid JSON: " + data); 
 
      } 
 
     } 
 
    }); 
 
})(jQuery); 
 

 

 

 

 
var date = '{"date": "\\/Date(1498435200000)\\/"}'; 
 
var desDate = $.parseJSON(date, true); 
 
console.log(desDate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+1

我一定会试试这个。在这个问题上已经有一段时间了,而且已经很累了。看起来没有足够接近我失去它的部分。感谢您的帮助! – AllramEst

相关问题