Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.NET Primitive Types - use Decimal instead of Double

Tags:

c#

json.net

How can I make JSON.NET return a decimal instead of a double when parsing floats from JSON? (it's an object with a Dictionary<string,object> that is serialized).

I've tried writing a JsonConverter but the CanConvert method doesn't get called with a Double type in order to try and convert it. There's other code regarding overriding JsonTextReader but this doesn't seem possible in the latest versions of Json.Net.

like image 573
James Crowley Avatar asked Mar 25 '13 14:03

James Crowley


People also ask

What are the different types of numeric types in JSON?

Numeric types¶. There are two numeric types in JSON Schema: integer and number. They share the same validation keywords. Note. JSON has no standard way to represent complex numbers, so there is no way to test for them in JSON Schema. The integer type is used for integral numbers.

Is it possible to convert a JSON file to double?

That is, although the spec format name is "double", in JSON or XML this necessarily means "decimal approximation of double", so by converting on the client side back to double you're only approximating an approximation. Having only one level of approximation, taking the decimal conversion, would be better.

What is the difference between dynamic and untyped JSON objects?

In Json.NET, dynamic properties are serialized and deserialized exactly the same as untyped objects: because dynamic isn't an actual type, Json.NET falls back to deserializing the JSON as LINQ to JSON objects. The second usage of dynamic in .NET are by the types that implement IDynamicMetaObjectProvider.

What types are converted from IEnumerable to JSON arrays?

.NET lists (types that inherit from IEnumerable) and .NET arrays are converted to JSON arrays. Because JSON arrays only support a range of values and not properties, any additional properties and fields declared on .NET collections are not serialized.


1 Answers

In Json.NET 5.0, Newtonsoft.Json.JsonSerializerSettings class has the new property FloatParseHandling, you can set this property value Newtonsoft.Json.FloatParseHandling.Decimal

like image 53
Nikoloz Pachuashvili Avatar answered Oct 16 '22 14:10

Nikoloz Pachuashvili