0

Call me crazy, but I was under the impression that there was a convention of try which meant give it a go, but if you can't then get back to me and let me know that it was a "no-go".

I have recently started a new project and I have decided to use System.Text.Json instead of Newtonsoft since it has been out for a while now and I like to play with new things.

I have the following bit of code in a JsonConverter:

using (var jsonDoc = JsonDocument.ParseValue(ref reader))
{
    if (jsonDoc.RootElement.TryGetInt32(out int number))
    {
    }
}

When it is a number, it works awesomely, but when it is anything but a number, it throws as if I was calling GetInt32().

In the custom converter, I sometimes get a number back, but I also can get an object back which contains the number that I am expecting as well as a string. I thought that I would be able to test for this using the TryGetInt32 method.

I have two questions:

  1. How could I test if I am getting the number back, or getting the number AND the string?, and
  2. What is the difference between TryGetInt32(out int number) and GetInt32()?
spovelec
  • 369
  • 1
  • 4
  • 20

2 Answers2

1

first question : using int.TryParse(variable,result) : this return bool and store variable if integer in result example:

 string json = "5";
        int result;
        if (int.TryParse(json, out result))
        {
            Console.WriteLine(result);
        }

second question: TryGetInt32(Int32) :Attempts to represent the current JSON number as an Int32 and return bool . Getint32(): get specific value as int32 in this case you must be sure that the value is integer

  • When I use TryGetInt32, it throws rather than returning false, which is what I would expect from GetInt32. – spovelec Sep 07 '21 at 12:09
1

TryGetInt32 throws exception if the value is not a number type.

It does not throw and returns false if the value is a number type but not a number kind convertible to int32.

I hope the following additional check helps:

using (var jsonDoc = JsonDocument.ParseValue(ref reader))
{
    if(jsonDoc.RootElement.ValueKind == JsonValueKind.Number &&
       jsonDoc.RootElement.TryGetInt32(out int number))
    {
    }
}