0

I have a program that loops through json and grabs the values. This works find until it gets to an integer that is above what int32 handles.

2021-09-10 08:00:02.7576|ERROR|System.OverflowException: Value was either too large or too small for an Int32.

Is it possible to handle both int32 and int64 in the below? I've tried to use the following but it didn't seem to work

int amount = (int)resource.First.ToObject<long>();
foreach (JToken resource in resources["responseData"]["resources"].ToList())
                  {
                     string propName = resource.ToObject<JProperty>().Name;
                            //int amount = (int)resource.First.ToObject<long>();
                            int amount = resource.First.ToObject<int>();
                            if (resDef["id"]?.ToString() == propName)
                     {
1
  • 2
    Just use long if values can exceed int.MaxValue ... Commented Sep 10, 2021 at 11:19

1 Answer 1

1

There is no way around using 'long'. In the commented out code the overflow exception happens after the JToken was cast and returned, when you take your long value and try to stuff it into the int with the static cast. Try this:

long amount = resource.First.ToObject<long>();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.