You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have seen inconsistent behavior of JsonConvert.DeserializeObject() for the decimal property whose value starts with 0. Please find the below code in C#.
using Newtonsoft.Json;
using System;
namespace Example
{
class Program
{
static void Main(string[] args)
{
var jsonExample1 = "{ \"amount\": 01234 }";
var jsonExample2 = "{ \"amount\": 0800 }";
try
{
// CASE #1
var example1 = JsonConvert.DeserializeObject<Example>(jsonExample1); // Sets the Amount = 668
Console.WriteLine(example1.Amount);
// CASE #2
var example2 = JsonConvert.DeserializeObject<Example>(jsonExample2); // throws an error - Input string '0800' is not a valid decimal.
Console.WriteLine(example2.Amount);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public class Example
{
public decimal Amount { get; set; }
}
}
Output:
Expected behavior
In CASE 1 => It should set the Amount = 1234 or 01234
In CASE 2 => It should set the Amount = 0800 or 800
Actual behavior
In CASE 1 => It sets the Amount = 668
In CASE 2 => It is throwing an error - "Input string '0800' is not a valid decimal."
Steps to reproduce
Create a sample console application in .Net Core and replace the program.cs code with the above code.
The text was updated successfully, but these errors were encountered:
@bartelink - the mentioned writeup explains to me CASE 2 which means it is throwing an invalid value. But what about CASE 1, there also it should have thrown the same error, but it is not. Instead, it is calculated as some other value, that is the real concern about the issue. Is that also known /by design?
var jsonExample1 = "{ \"amount\": 01234 }";
JsonConvert.DeserializeObject<Example>(jsonExample1); // Why this sets the Amount = 668
Yes, if you read on, you'll see it's being interpreted as octal (base 8). You'll also see that this is a debatable but not uncommon interpretation from the point of view of 'standard' JSON, insofar as that exists. I have not drilled in to the issue and/or the code to see whether it's still hard-wired - that's your opportunity ;)
Bug:
I have seen inconsistent behavior of JsonConvert.DeserializeObject() for the decimal property whose value starts with 0. Please find the below code in C#.
Output:
Expected behavior
In CASE 1 => It should set the Amount = 1234 or 01234
In CASE 2 => It should set the Amount = 0800 or 800
Actual behavior
In CASE 1 => It sets the Amount = 668
In CASE 2 => It is throwing an error - "Input string '0800' is not a valid decimal."
Steps to reproduce
Create a sample console application in .Net Core and replace the program.cs code with the above code.
The text was updated successfully, but these errors were encountered: