2

Since Json has only one type for Number, but C# has many types, like int, long, double, decimal, etc., when I use Utf8JsonReader, what is the correct way to retrieve number when after I call Read() and the TokenType is JsonTokenType.Number?

There are APIs such as GetInt32, GetInt64, GetDouble, GetDecimal, etc. and their TryGet... equivalents, but there is no clear indication of what C# type to use for given number value until one of these is actually called.

The only way I see right now is to call TryGet... APIs starting with the smallest I m interested in, e.g. TryGetInt32(), TryGetInt64(), TryGetFloat(), TryGetDouble(), until one of these succeeds. Even that is not clear since e.g. GetDouble() will succeed, even if the number of digits is too large for double, by rounding it. Is there any way to configure these APIs to succeed only if there is no loss of precision?

I guess I m just confused as to what is generally done when reading numbers with Utf8JsonReader.

Yevgeniy P
  • 1,480
  • 1
  • 15
  • 23
  • Could you please share the example JSON and code for its reading? – Pavel Anikhouski May 02 '20 at 08:49
  • Typically one knows the schema of what you are deserializing / reading into. If your business rules or models dictate that the property should be an int, use `GetInt32`; if they call for a double then `GetDouble` – pinkfloydx33 May 02 '20 at 14:02
  • The problem is that I don't know the schema, this code is part of a library that provides a generic representation of value. The user of the library would know the schema and call one of corresponding Get... methods. I guess I was looking for something similar to Java Jackson Json parser where the number value will be read into the correct corresponding subclass of Number. If I want to avoid loss of precision, it seems for C# decimal has greatest precision, but it cannot represent value range of double. – Yevgeniy P May 04 '20 at 03:01

0 Answers0