4

In my C# project, I have occasion to deserialize JSON that may not be correct. Hence, errors are possible. At the moment, I am wrapping it in a try block, and catching exceptions by returning null. This works, but it would be nicer to tell the library not to throw an exception in the first place. Is that possible?

My current code:

public static NodeModel FromJsonString(string json)
{
  NodeModel r = null;
  JsonConverter converter = JsonConverters.ReferenceHierarchyCreation;
  try
  {
    r = JsonConvert.DeserializeObject<NodeModel>(json, converter);
  }
  catch
  {
  }
  return r;
}
William Jockusch
  • 26,513
  • 49
  • 182
  • 323
  • If you passed that parameter in, how would you tell the difference between invalid JSON and it returning `null` for a valid JSON string (ie if it was trying to deserialise `"null"`)? Right now what you're doing is probably the best you can do, since it's in your layer where you can make the decision that `"null"` and `this: 'isn't, valid [json` should be treated the same. – James Thorpe Apr 25 '16 at 15:29

1 Answers1

3

but it would be nicer to tell the library not to throw an exception in the first place

There are no TryParse group of methods with JSON parsing. What you have right now is probably what you can do.

Another option would be to validate your JSON against a Schema and only parse if the JSON is valid.

Just to add, the only thing would be to catch the actual exception and log it somewhere, but If you are only interested in parsing and ignoring exception than your solution is good enough.

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436