I’m coding using C#.
When GET request, I get json format string like
{ "code": 2312, "price": 98.322, ... }
to parse, I use System.Text.Json.JsonDocument.Parse(jsonString) function.
I think they’re type-casting internally.
But because of the floating-point error, I want JsonDocument.Parser to parse the string as it is.
You can also create a class and use JsonSerializer.Deserialize, but it is cumbersome because there are too many json properties.
2
Answers
I struggled a little to understand your error here, but from what i gathered it seems you want to process the numbers as strings, this can be done by adding options to your json serialiser:
You can configure this behavior using
JsonSerializerOptions.NumberHandling
property which has the following values:You will wan to use
NumberHandling = JsonNumberHandling.Strict
. The default value for ASP.NET Core isJsonNumberHandling.AllowReadingFromString
. From .NET 9 onwards you will be able to access the defaults this using theJsonSerializerOptions.Web
singleton (See MS Docs – Web defaults forJsonSerializerOptions
).You can configure this as a parameter to
JsonSerailizer.Deserialize()
).If you were to change the properties to types
int
andfloat
/double
you would get aJsonException
when parsing.Or, you can also configure this globally using AddJsonOptions() for all your controllers in ASP.NET Core:
However, once you make you object properties
string
s which you will have to do, you can omit to specify theNumberHandling
since it then a conversion is no longer necessary.