How to force json.net to deserialize DataTable column from integer to float

二次信任 提交于 2019-12-11 11:59:58

问题


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

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

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.


回答1:


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.

You have 2 options:

  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)


来源:https://stackoverflow.com/questions/17467908/how-to-force-json-net-to-deserialize-datatable-column-from-integer-to-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!