问题
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:
- 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
- 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