使用ASP.NET将json字符串转换为datatable? [英] Convert json string to datatable using ASP.NET?

查看:200
本文介绍了使用ASP.NET将json字符串转换为datatable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我传递整数值时,JsonData支持Datatable。当我传递十进制值时,我收到错误..LIke





Here JsonData supports to Datatable when I Pass Integer values..When I Pass Decimal values I am getting error ..LIke


var dt1 = JsonConvert.DeserializeObject<DataTable>(jsonData);



输入字符串的格式不正确。不能存储< 1.5>在VAT栏中。







这里DataTable也接受十进制值..



我尝试过:



如果我传递整数值,那么它接受JSON DATA到DataTable
当我通过十进制时,
,然后我收到错误?


Input string was not in a correct format.Couldn't store <1.5> in VAT Column.



Here DataTable Accept Decimal values also..

What I have tried:

IF I Pass Integer values then it accepts JSON DATA to DataTable
when i Pass Decimal ,then I am getting error?

推荐答案

问题是 DataTableConverter [ ^ ]使用第一行的值来确定列的数据类型。由于第一行在 VAT 列中有一个整数,因此该列声明为 Int64 。当它尝试将值 1.5 反序列化为整数时,它将失败并显示错误:

The problem is that the DataTableConverter[^] uses the values of the first row to determine the data-types for the columns. Since the first row has an integer in the VAT column, the column is declared as Int64. When it tries to deserialize the value 1.5 as an integer, it fails with the error:
Error converting value "1.5" to type 'System.Int64'.



可以获取 DataTableConverter的来源并根据您的需要进行修改。但是,更简单的解决方案是使用从 DataTable 派生的特定类,该类定义其构造函数中的列:


You could take the source of the DataTableConverter and modify it to suit your needs. However, a simpler solution would be to use a specific class derived from DataTable which defines the columns in its constructor:

internal class StatesTable : DataTable
{
    public StatesTable()
    {
        Columns.Add("Stateid", typeof(int));
        Columns.Add("VAT", typeof(decimal));
        Columns.Add("CST", typeof(decimal));
    }
}
...
DataTable dt1 = JsonConvert.DeserializeObject<StatesTable>(jsonData);


这篇关于使用ASP.NET将json字符串转换为datatable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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