JToken Array to Data Table C#

Viewed 625

I have a JSON result with the following structure:

{
"property1":1,
"property2":[[1,"A"],[2,"B"],[3,"C"],...] // Possible to get >10000 values
}

Using the above JSON data format, I am only interested to get the array values from the property2 which contains an array of array values and convert it to data table.

The above JSON result is coming from an external WEB API and here is what I have currently:

var jsonResponse = API.RetrieveData();
JObject json = JObject.Parse(jsonResponse);           
JToken[] A = json["property2"].ToArray();

Logically, I can loop on the elements of Array [] A column by column and add it to the predesigned data table. My problem is that, upon using this, the performance will be affected as in most cases, the data that will be retrieved from the API is > 10000 values.

Is there any specific way to convert this kind of JSON Format to DataTable in c# with the most efficient way?

Thank you in advance.

1 Answers

I have Better and Fast approach for You

Step 1

Create a class that is similar to json structure

public class JsonClass
{
   public string property1 { get ; set; }
   public List<Dictionary<int,string>> property2 { get ; set; }
}

Step 2

Use Newtonsoft and deserialize json input to json match class

JsonClass jsonClass = JsonConvert.DeserializeObject<JsonClass>(jsonInputString);

Step 3

if you are using WPF just use

datatable.ItemSource = jsonClass ;

if you are using Winform then use BindingSource Component

BindingSource binding = new BindingSource();
binding.DataSource = jsonClass;
datatable.DataSource = binding;

Result might be

property1 | property2
---------------------------------------
"A"       |  Collection 

Good luck

Related