Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal precision of zero when serializing doubles to JSON

Tags:

json

c#

json.net

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).

like image 210
Steven Liekens Avatar asked Jan 18 '14 17:01

Steven Liekens


1 Answers

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)

like image 174
Jack Avatar answered Oct 11 '22 11:10

Jack