如何强制json.net将DataTable列从整数反序列化为float

问题描述:

我正在尝试将json序列化为数据表.我的JSON如下所示: [{ "Id":35, 名称":"ABC", "XVar":0.078814, "YVar":1 }, { "Id":79, 名称":"XYZ", "XVar":1.50, "YVar":30.2 }]

I am trying to desrialize a json into a datatable. My JSON looks like below: [{ "Id": 35, "Name": "ABC", "XVar": 0.078814, "YVar": 1 }, { "Id": 79, "Name": "XYZ", "XVar": 1.50, "YVar": 30.2 }]

我正在使用以下代码反序列化: var dataTable =(DataTable)JsonConvert.DeserializeObject(jsonString,(typeof(DataTable)));

I'm using the following code to deserialize: var dataTable = (DataTable)JsonConvert.DeserializeObject(jsonString, (typeof(DataTable)));

问题是第二个对象的Y值序列化为30,而不是30.2.保存数据最简单的方法是什么.欢迎所有想法.

The problem is that the Y value for the second object is serialized as 30 and not 30.2. What is the simplest thing I can do to preserve the data. All ideas are welcome.

您面临的问题是,默认情况下,用于序列化和反序列化DataTable类型的Json.Net DataTableConverter使用第一个json字符串中的object对象,以检测每一列的值的类型.由于第一个对象上的YVar是整数,因此它假定该列上的所有其他对象也将是整数.

The problem you are facing is that by default, the Json.Net DataTableConverter which is used to serialize and deserialize the DataTable type, uses the first object within the json string to detect the type of the value for each column. Since YVar on the first object is an integer, then it assumes all other objects will be integers as well on that column.

您有2个选择:

  1. 即使您将值设置为int值,也应将其格式设置为浮点型,在这种情况下,您的json字符串应为"YVar": 1.0 ,而不是"YVar": 1
  2. 使用json.net DataTableConverter 并根据您的需求进行定制.这将要求您使用JsonConvert.DeserializeObject(string value, Type type, params JsonConverter[] converters)
  3. 的重载
  1. Format your values as floats even when they are int values, in this case, your json string should have "YVar": 1.0 instead of "YVar": 1
  2. Take json.net DataTableConverter source and tailor it to your needs. This would require you to use the overload of JsonConvert.DeserializeObject(string value, Type type, params JsonConverter[] converters)