ReadAsDecimal - not ideal really is it?

Jan 4, 2013 at 1:32 PM
Edited Jan 4, 2013 at 1:35 PM

Hi,

Thought would post here since have some issues with how ReadAsDecimal has been included in the API.

I find it strange that you have to know which version of Read to call before you call it, otherwise risk losing information. I notice there are other special case Read methods too, and guess these may have the same issue.

It can be illustrated by using a modified version of the case I posted in this thread: http://json.codeplex.com/workitem/23761

Try:

    JsonTextReader reader = new JsonTextReader(new StringReader("1234567890.123456"));
    var settings = new JsonSerializerSettings();
    var serialiser = JsonSerializer.Create(settings);

     reader.Read();
    decimal? d = serialiser.Deserialize<decimal?>(reader);
    System.Diagnostics.Debug.WriteLine(d);

Versus:

    JsonTextReader reader = new JsonTextReader(new StringReader("1234567890.123456"));
    var settings = new JsonSerializerSettings();
    var serialiser = JsonSerializer.Create(settings);

    reader.ReadAsDecimal();
    decimal? d = serialiser.Deserialize<decimal?>(reader);
    System.Diagnostics.Debug.WriteLine(d);

The first truncates the decimal, the second does not.
Interestingly, not calling Read, like my originally posted version, works too.

These seems like madness to me!
Have got around the issue for now since happen to be in a custom converter already, so can use T to determine what version of Read to call, but am waiting for it to come and bite me again basically; especially outside of the specific class converter.

 

Another way I thought of solving the issue was to write a custom converter to handle Decimals specifically, unfortunately though, since the value has already been read into a Double, the damage has been done.
If an OriginalValue (string) was included in the JsonReader then it may be solvable - I don't want to use reflection to get at the _chars array...

Anyway, I'm okay for the immediate future, but thought would open a discussion on it, since I don't think it's ideal currently.
Would like to see one Read method cope with anything you can throw at it.

Regards,
Westy