This project has moved. For the latest updates, please go here.

Parse methods throw System.Exception

Oct 20, 2010 at 9:29 PM

I would like to be able to parse a JSON object from a string but be able to recover from a parsing error. However, JObject.Parse (as well as the other Parse methods) throws an exception of type System.Exception in some circumstances (e.g. parsing "false"). If I catch(Exception) I'll also be catching any number of potentially fatal errors. It would be really great if any parse-related exceptions would be wrapped in a common exception type like JsonException. Another idea would be to write a JToken.Parse method that is more flexible. Please let me know if I'm missing anything obvious. Thanks!

Oct 20, 2010 at 9:44 PM

Though my request to avoid throwing System.Exception still stands, I did find the JToken.ReadFrom method, which at least avoids the wrong-type Exception that JObject.Load throws.

public static class JsonUtility
  public static JToken Parse(string text)
    return JToken.ReadFrom(new JsonTextReader(new StringReader(text)));

It looks like JsonReaderException is consistently thrown on bad input, so I should be able to safely recover.