gpt4 book ai didi

javascript - 为 Google Charts 返回具有日期类型的 JSON 数组

转载 作者:行者123 更新时间:2023-11-30 00:23:43 26 4
gpt4 key购买 nike

我有一个来自 Google Charts 的“时间轴”图表。它在填充数据时需要 JavaScript 日期类型。

我的初始化代码是这样的:

var container = document.getElementById('divChart1');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();

dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'string', id: 'Category' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });

现在我正尝试通过 AJAX 填充它,但 Date 类型给我带来了问题。

需要像这样填充行:

dataTable.addRows([
['Aaa', 'A', new Date(2014, 1, 1), new Date(2016, 12, 31)],
['Bbb', 'B', new Date(2014, 1, 1), new Date(2016, 5, 31)]]);

有什么方法可以从我的 AJAX 服务返回一个序列化的集合并直接解析它,或者我是否需要每次迭代该集合并更新一个 JavaScript 日期?

当我尝试 dataTable.addRows(JSON.parse(result.chartData)); 时,我收到以下错误:错误:类型不匹配。值 2015-08-26T11:59:23.889004+02:00 与列索引 2 中的类型日期不匹配

出于信息目的,这是它在 AJAX 服务上的样子:

List<List<object>> chartData = new List<List<object>>();

chartData.Add(new List<object>() {
"Aaa",
"A",
DateTime.Now,
DateTime.Now.AddMonths(3)
});

return JsonConvert.SerializeObject(chartData);

编辑:好吧,我让它工作了。仍在调整,但这是要点:

chartData.Add(new List<object>() { 
"Aaa",
"A",
DateTime.Now.Year + "#" + DateTime.Now.Month + "#" + DateTime.Now.Day,
DateTime.Now.AddMonths(3).Year + "#" + DateTime.Now.AddMonths(3).Month + "#" + DateTime.Now.AddMonths(3).Day
});

var result = $.parseJSON(result.chartData);
$.each(result, function (k, v) {
var s = v[2].split('#');
var e = v[3].split('#');
dataTable.addRow([v[0], v[1], new Date(s[0], s[1], s[2]), new Date(e[0], e[1], e[2])]);
});

不会将其用作官方答案,因为它没有回答问题。

最佳答案

更新

虽然 JSON 是按照您的原始问题中的要求创建的,但它似乎 JSON.parse('new Date(2014, 1, 1)') 不起作用,因为 JavaScript 日期构造函数不是 strictly valid JSON .

因此看来您应该将 DateTime 序列化为 string 并将 reviver function 传递给识别日期字符串的 JSON.parse()并构造一个 JavaScript Date。例如:

原始答案

您可以扩展 JavaScriptDateTimeConverter 以写入和读取格式为 new Date(2014, 1, 1 [, H [, M [, S [, MS]]]])(我是扩展 this answer 只读不写):

public class JavaScriptYMDDateTimeConverter : JavaScriptDateTimeConverter
{
public bool StripTimeOfDay { get; set; }

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is DateTime)
{
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
// Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time.
var date = ((DateTime)value).ToLocalTime();

writer.WriteStartConstructor("Date");
writer.WriteValue(date.Year);
writer.WriteValue(date.Month - 1);
writer.WriteValue(date.Day);

if (!StripTimeOfDay)
{
var written = date.Date;
var epsilon = new TimeSpan(TimeSpan.TicksPerMillisecond);

// Only write hours, min, sec, ms if needed.
if (date < written - epsilon || date > written + epsilon)
{
writer.WriteValue(date.Hour);
written = written.AddHours(date.Hour);
}

if (date < written - epsilon || date > written + epsilon)
{
writer.WriteValue(date.Minute);
written = written.AddMinutes(date.Minute);
}

if (date < written - epsilon || date > written + epsilon)
{
writer.WriteValue(date.Second);
written = written.AddSeconds(date.Second);
}

if (date < written - epsilon || date > written + epsilon)
{
writer.WriteValue(date.Millisecond);
written = written.AddMilliseconds(date.Millisecond);
}
}
writer.WriteEndConstructor();
}
else
{
// DateTimeOffset
base.WriteJson(writer, value, serializer);
}
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Type type = (Nullable.GetUnderlyingType(objectType) ?? objectType);
bool isNullable = (Nullable.GetUnderlyingType(objectType) != null);

var token = JToken.Load(reader);
if (token == null || token.Type == JTokenType.Null)
{
if (!isNullable)
throw new JsonSerializationException(string.Format("Null value for type {0} at path {1}", objectType.Name, reader.Path));
return null;
}
if (token.Type != JTokenType.Constructor)
{
throw new JsonSerializationException(string.Format("Invalid Date constructor \"{0}\" at path {1}", token.ToString(), reader.Path));
}
var constructor = (JConstructor)token;
if (!string.Equals(constructor.Name, "Date", StringComparison.Ordinal))
{
throw new JsonSerializationException(string.Format("Invalid Date constructor \"{0}\" at path {1}", token.ToString(), reader.Path));
}

var values = constructor.Values().ToArray();

if (values.Length == 0)
{
throw new JsonSerializationException(string.Format("Invalid Date constructor \"{0}\" at path {1}", token.ToString(), reader.Path));
}
else if (values.Length == 1)
{
// Assume ticks
using (var subReader = constructor.CreateReader())
{
while (subReader.TokenType != JsonToken.StartConstructor)
subReader.Read();
return base.ReadJson(subReader, objectType, existingValue, serializer); // Use base class to convert
}
}
else
{
var year = (values.Length > 0 ? (int)values[0] : 0);
var month = (values.Length > 1 ? (int)values[1] : 0) + 1; // c# months go from 1 to 12, JavaScript from 0 to 11
var day = (values.Length > 2 ? (int)values[2] : 0);
var hour = (values.Length > 3 ? (int)values[3] : 0);
var min = (values.Length > 4 ? (int)values[4] : 0);
var sec = (values.Length > 5 ? (int)values[5] : 0);
var ms = (values.Length > 6 ? (int)values[6] : 0);

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
// Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time.
var dt = new DateTime(year, month, day, hour, min, sec, ms, DateTimeKind.Local);
if (type == typeof(DateTimeOffset))
return new DateTimeOffset(dt);
return dt;
}
}
}

然后像这样使用它:

        var settings = new JsonSerializerSettings { Converters = new JsonConverter[] { new JavaScriptYMDDateTimeConverter { StripTimeOfDay = true } } }; 
return JsonConvert.SerializeObject(chartData, settings);

哪些输出

[["Aaa","A",new Date(2015,7,26),new Date(2015,10,26)]]

关于javascript - 为 Google Charts 返回具有日期类型的 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32223784/

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