Wednesday, August 10, 2022

[FIXED] How to deserialize decimal property with precision

Issue

In my WEb Api I am returning json like this:

  class Test
  {
    public decimal Dec { get; set; }
  }

  Test test = new Test() { Dec = 1.00m };
  var json = JsonConvert.SerializeObject(test, Formatting.Indented);
  return json;

Currently, the json is

{
  "Dec": 1.00
}

I am trying to test it like this:

var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
var decimalValue = dictionary["Dec"]; // I am expecting 1.00 but it is 1

It is getting 1 instead of 1.00. But when I do:

        var myTest = JsonConvert.DeserializeObject<Test>(json);
        var decimalValue = myTest.Dec; // It is 1.00 

It is getting 1.00. But the problem is I cannot use Test class on my tests. Question is why after deserializing it to dictionary it is 1? Should I create a new class like 'Test' or is there any way to solve this?


Solution

So, Setting FloatParseHandling to Decimal in JsonSerializerSettings solved my problem:

    var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(json, new JsonSerializerSettings() { FloatParseHandling = FloatParseHandling.Decimal });
    var decimalValue = dictionary["Dec"]; 


Answered By - Dilshod K
Answer Checked By - Terry (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.