Steven Liekens
Steven Liekens

Reputation: 14088

Decimal precision of zero when serializing doubles to JSON

Consider the following JSON object:

{
    "value": 0   
}

Now suppose I'm mapping this to a .NET type Foo:

class Foo
{
    public double Value { get; set; }
}

The type of Foo.Value is double, because Value isn't always an integer value.

Using JSON.NET, this works beautifully:

Foo deserialized = JsonConvert.DeserializeObject<Foo>(json);

However, observe what happens when I try to convert the object back to its JSON representation:

string serialized = JsonConvert.SerializeObject(deserialized, Formatting.Indented);

Output:

{
  "Value": 0.0
}

Notice the trailing zero? How do I get rid of it?

EDIT

I suspect that the answer will be write your own converter. If it is, then that's fine and I guess I'll accept that as the answer. I'm just wondering if perhaps there exists an attribute that I don't know of that lets you specify the output format (or similar).

Upvotes: 9

Views: 5893

Answers (1)

Jack
Jack

Reputation: 1084

It appears that this is a hard-coded behavior of the library:

https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonConvert.cs#L300

If you want to alter the behavior you'll need to edit the library and recompile from source (or choose another JSON library)

Upvotes: 6

Related Questions