0

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.

1
  • Just put them in the array and then serialize it. Commented Mar 16, 2017 at 12:17

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.