繁体   English   中英

将JSON转换为DataTable在c#中返回空结果

[英]Convert JSON to DataTable returns empty result in c#

我正在尝试将我的 json 数据转换为数据表。 遵循了这篇文章中的所有方法以及所有建议的链接在 stackoverflow 上,尝试了很多方法,但仍然没有结果。

我的方法看起来像:

    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);
    }

示例json是执行方法后:

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

也尝试过类:

    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; }
    }

我用于将 json 转换为数据表的扩展方法:

    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;        
    }

我检查了你的代码:

        static void Main() {
        string 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\"}]";

        System.Data.DataTable dt = (System.Data.DataTable)JsonConvert.DeserializeObject(json, (typeof(System.Data.DataTable)));
        Console.WriteLine(dt);

        for (int i = 0; i < dt.Columns.Count; i++) {
            Console.Write(dt.Columns[i] + " | ");
        }
        Console.WriteLine();
        for (int j = 0; j < dt.Rows.Count; j++) {

            for (int i = 0; i < dt.Columns.Count; i++) {
                Console.Write(dt.Rows[j].ItemArray[i] + " | ");
            }
            Console.WriteLine();

        }
    }

输出:

身份证 | 网罩 | 网关 | jenkinsUrl | 桥| ip范围|

1 | 22 | 10.19.0.1 | http://10.19.0.20:31000 | br0 | 10.19.0.1-10.19.3.254 |

11 | 22 | 10.23.0.1 | http://10.12.3.12:33355 | br2 | 10.23.0.4-10.23.0.20 |

看来,数据表被填满了

从 JSON 反序列化为自定义对象列表很简单:

List<NetworkDto> networkList = JsonConvert.DeserializeObject<List<NetworkDto>>(json);

就是这样! 现在您的networkList变量是一个 NetworkDto 对象列表。 如果您想验证它们是否在控制台中,您可以将它们全部写出到控制台:

foreach(var network in networkList)
(
    Console.WriteLine($"Network Id {network.Id}");
)

暂无
暂无

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

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