Monday, March 25, 2019

JsonConvert.DeserializeObject exception when dynamic value not available

Not sure how to handle a dynamic input not being available

Input - {Name: 'bob', Age: '22', Weight: 'Fat"}

dynamic decoded_JSON = JsonConvert.DeserializeObject<dynamic>(return_value); string Name = decoded_JSON.Name; string Age = decoded_JSON.Age; string Weight = decoded_JSON.Weight; Console.WriteLine(Name, Age, Weight); 

This is fine,

However if I use the input {Name: 'bob', Age: '22'}

I get an exception because Weight doesn't exist. (Error: System.NullReferenceException: Object reference not set to an instance of an object)

Is there a way to smartly handle a dynamic variable not being available?

Thanks!

JsonConvert.DeserializeObject<dynamic> exception when dynamic value not available Click here
  • Blogger Comment
  • Facebook Comment

0 comments:

Post a Comment

The webdev Team