I am trying to convert my json data to data table. Followed all approaches from this post and also all suggested links all over stackoverflow, tried many ways but still no result.
My method looks like:
public static async Task GetManagements()
{
Console.WriteLine("Getting managements");
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
await Token.GetToken());
HttpResponseMessage response = await client.GetAsync(LibvirtUrls.managementUrl);
HttpContent content = response.Content;
Console.WriteLine("Response Status Code: " + (int)response.StatusCode);
string result = await content.ReadAsStringAsync();
var json = Helpers.FormatJson(result);
Console.WriteLine("json");
Console.WriteLine(result); // for testing
Console.WriteLine(new string('-',35));
Console.WriteLine("formatted");
Console.WriteLine(json); // for testing
// I used both result and json (formatted and not formatted one)
Console.WriteLine(new string('-',35));
List<NetworkDto> networkList =
JsonConvert.DeserializeObject<List<NetworkDto>>(json);
Console.WriteLine("table view");
var ss = networkList.ToDataTable<NetworkDto>();
Console.WriteLine(ss);
}
Sample json is after executing method:
Getting managements as json
Response Status Code: 200
json
[{"id":1,"netMask":22,"gateway":"10.19.0.1","jenkinsUrl":"http://10.19.0.20:31000","bridge":"br0","ipRange":"10.19.0.1-10.19.3.254"},{"id":11,"netMask":22,"gateway":"10.23.0.1","jenkinsUrl":"http://10.12.3.12:33355","bridge":"br2","ipRange":"10.23.0.4-10.23.0.20"}]
------------------------------------------
formatted
[
{
"id":1,
"netMask":22,
"gateway":"10.19.0.1",
"jenkinsUrl":"http://10.19.0.20:31000",
"bridge":"br0",
"ipRange":"10.19.0.1-10.19.3.254"
},
{
"id":11,
"netMask":22,
"gateway":"10.23.0.1",
"jenkinsUrl":"http://10.12.3.12:33355",
"bridge":"br2",
"ipRange":"10.23.0.4-10.23.0.20"
}
]
------------------------------------------------
table view
Tried also with class:
public class NetworkDto
{
public int Id { get; set; }
public int NetMask { get; set; }
public string Gateway { get; set; }
public string JenkinsUrl { get; set; }
public string Bridge { get; set; }
public string IpRange { get; set; }
}
Extension method I am using for converting json to data table:
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for(int i = 0 ; i < props.Count ; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
>(json);`?
– mason Feb 27 '20 at 14:53