What I need:
- Deserialize Json string to and object
- Do some stuff
- return it as a string at the end
What is the problem?
When Json has property like {"foobar" : 0.0000000000000000001}, it is converted as a number, but then as a string it is represented in scientific notation as 1E-19
Is there a way to read number from json as a string, or convert such a number later to exact same string, without any precision loss? Precision is not fixed and number in json can occur in any property.
Usage of Newtonsoft is preferable (if it’s possible) over System.Text.Json
I’ve tried to
- create Newtonsoft’s CustomJsonConverter
- use System.Text.Json.JsonNumberHandling.WriteAsString
- converting float to string
but any of this solutions didn’t work - I couldn’t find a way to treat any number value as a string, idk if it’s even possible in such converter
- This one I think works only one way, from obj to string, and this is not what I’m looking for
- such a conversion didn’t work because it lost a precision, or did "over precision" (0.00…01 was written as 0.00…0989919999 or smth like this), or added additional zeros at the end – depends what formatting I’ve used
Ideally I’d like to convert string like {"foobar": 21.37} to object with property foobar = "21.37" to be sure that any precision won’t be lost after coverting between number/string
Minimal Reproducible Example
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
var json = """
[{
"foobar1": 21.37000,
"foobar2": 0.0000000000000000001000,
"foobar3": 1.1000E-19,
"aReallyBigInteger" : 1111199999999999999999999999999999999911111
}]
""";
var input = JsonConvert.DeserializeObject<JToken>(json);
Console.WriteLine(input);
/*
Expected result:
[
{
"foobar1": "21.37000",
"foobar2": "0.0000000000000000001000",
"foobar3": "1.1000E-19",
"aReallyBigInteger": "1111199999999999999999999999999999999911111"
}
]
Current Behavior:
[
{
"foobar1": 21.37,
"foobar2": 1E-19,
"foobar3": 1.1E-19,
"aReallyBigInteger": 1111199999999999999999999999999999999911111
}
]
*/
2
Answers
MY SOLUTION
Smelly code but the one that worked for me.
Probably terrible efficiency but only one that meets my requirements.
I tried building a custom Converter class like the one shown below and used it to deserialize a JSON string containing numbers, and it seems to be returning the numbers as string without losing any precision. Please give it a try and let me know if it works.