简体   繁体   中英

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:

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:

[["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.

My related technologies include MVC5, jQuery, and JSON. I've tried using JSON.stringify and JSON.parse , but the data won't come over correctly.

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.

There is no direct way out there to serialized C# objects to JSON Array. You can achieve this either

  • By converting C# objects to C# Array and then serialise the array as JSON.
  • Use Javascript to convert serialised objects to 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. Hope that solves your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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