PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] How to deserialize decimal property with precision

 August 10, 2022     c#, decimal, deserialization, json     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing