简体   繁体   English

如何使用JSON将C#对象转换为Javascript数组?

[英]How do I convert a C# object into a Javascript array of arrays using JSON?

I'm trying to convert an object of the following C# class type into a Javascript array of arrays: 我正在尝试将以下C#类类型的对象转换为数组的Javascript数组:

public class SankeyData
{
  public string Source { get; set; }
  public int Width { get; set; }
  public string Destination { get; set; }
}

The array of arrays in Javascript needs to look like this: Javascript中的数组的数组应如下所示:

[["Link1",10,"Link2"],["Link3",20,"Link4"],["Link5",30,"Link6"]]

Is there an easy way to do the conversion? 有没有简单的方法可以进行转换? I'm using a jQuery $.getJSON to get the data from a C# controller action. 我正在使用jQuery $.getJSON从C#控制器操作获取数据。

My related technologies include MVC5, jQuery, and JSON. 我的相关技术包括MVC5,jQuery和JSON。 I've tried using JSON.stringify and JSON.parse , but the data won't come over correctly. 我尝试使用JSON.stringifyJSON.parse ,但是数据不会正确JSON.stringify

Here's what I have so far: 这是我到目前为止的内容:

$.getJSON('/Application/Sankey', { id: @Model.ID }, function (data) {
  $.each(data, function (i, item) {
    sankey.setData(JSON.stringify(item));
  });
});

Which gives a close result, but not quite what I need: 这给出了接近的结果,但不是我所需要的:

[{"Source":"Link1","Width":10,"Destination":"Link2"},{"Source":"Link3","Width":20,"Destination":"Link4"},{"Source":"Link5","Width":30,"Destination":"Link6"}]

NOTE : I'm already using an MVC @model for something else in the page so I can't just set the @model to the SankeyData class. 注意 :我已经在页面@model MVC @model用于其他内容,所以我不能只将@model设置为SankeyData类。

There is no direct way out there to serialized C# objects to JSON Array. 没有直接的方法可以将C#对象序列化为JSON Array。 You can achieve this either 您可以实现这一目标

  • By converting C# objects to C# Array and then serialise the array as JSON. 通过将C#对象转换为C#数组,然后将该数组序列化为JSON。
  • Use Javascript to convert serialised objects to JSON Array. 使用Javascript将序列化的对象转换为JSON Array。

I would recommend second option as array is heterogeneous. 我建议第二个选择,因为数组是异构的。

Something like this: 像这样:

 function objectsToArray(data, columns) { var dataArray = []; for (var i in data) { var itemArray = []; for (var j in columns) { itemArray.push(data[i][columns[j]]); } dataArray.push(itemArray); } return dataArray; } data = [{"Source":"Link1","Width":10,"Destination":"Link2"},{"Source":"Link3","Width":20,"Destination":"Link4"},{"Source":"Link5","Width":30,"Destination":"Link6"}] console.log(objectsToArray(data, ["Source", "Width", "Destination"])); 

So, just pull data using $.getJSON and the feed to objectsToArray with key names in order. 因此,只需使用$.getJSON和提要按objectsToArray使用键名将数据提取到objectsToArray Hope that solves your problem. 希望能解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM