如何创建基于JSON的数据表反序列化JArray数据? [英] how to create the datatable based on the Json deserialized JArray Data?

查看:681
本文介绍了如何创建基于JSON的数据表反序列化JArray数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经撂荒JArray数据。我需要动态创建基于需要插入数据后,在Jarray列名的DataTable。

I have fallowing JArray data . I need to create a datatable dynamically based on the column names in the Jarray after that need to insert the data.

能否请你帮我做这个操作。

Can you please help me to do this operation.

<pre>

{[
{
"PID": 3,
"FirstName": "parveen",
"LastName": "a",
"Gender": "male"
},
{
"PID": 8,
"FirstName": "ramarao",
"LastName": "M",
"Gender": "male"
}
]}
</pre>

在此先感谢

普尔纳

推荐答案

您JSON输入无效。应删除第一个和最后一个支架,因为它是一个数组,而不是一个对象。如果您知道行类型,你应该使用现有的JSON的图书馆之一,数组反序列化到一个强类型列表。如果你不知道的类型,使用方法toDataTable

Your JSON input is not valid. You should remove the first and the last brackets, since it is an array, not an object. If you know the row type you should use one of the existing JSON libraries, and deserialize the array to a strongly typed list. If you don't know the type, use the toDataTable method.

我用下面的库中的例子:

I used the following library in the example:

http://james.newtonking.com/json

    private static void Main(string[] args)
    {
        var data =
            "[{\"PID\": 3,\"FirstName\": \"parveen\",\"LastName\": \"a\",\"Gender\": \"male\"},{\"PID\": 8,\"FirstName\": \"ramarao\",\"LastName\": \"M\",\"Gender\": \"male\"}]";

        var dattable = toDataTable(data);

        var list = toList(data);
    }

    class User
    {
        public int PID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
    }

    private static List<User> toList(string json)
    {
       return Newtonsoft.Json.JsonConvert.DeserializeObject<List<User>>(json);
    } 

    private static DataTable toDataTable(string json)
    {
        var result = new DataTable();
        var jArray = JArray.Parse(json);
        //Initialize the columns, If you know the row type, replace this   
        foreach (var row in jArray)
        {
            foreach (var jToken in row)
            {
                var jproperty = jToken as JProperty;
                if (jproperty == null) continue;
                if (result.Columns[jproperty.Name] == null)
                    result.Columns.Add(jproperty.Name,typeof(string));
            }
        }
        foreach (var row in jArray)
        {
            var datarow = result.NewRow();
            foreach (var jToken in row)
            {
                var jProperty = jToken as JProperty;
                if (jProperty == null) continue;
                datarow[jProperty.Name] = jProperty.Value.ToString();
            }
            result.Rows.Add(datarow);
        }

        return result;
    }

这篇关于如何创建基于JSON的数据表反序列化JArray数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆