23

In my application I'm using newtonsoft to serialize and deserialize object, I want to know is there any built in API to determine that input string can deserialize to specific object or not?

public TObject Deserialize<TObject>(string serialized)
{   
    /// I want check the condition, and if is not serialized string just return default(TObject)     
    return JsonConvert.DeserializeObject<TObject>(serialized);
}

I don't want to use try catch. Currently I implemented like that but looking to find a way to verify the string before start to deserialize object.

Already I saw this question Deserialize json in a "TryParse" way, but its not my answer cause I don't have any specific schema and JSON format can change dynamically.

Community
  • 1
  • 1
Peyman
  • 3,068
  • 1
  • 18
  • 32
  • 2
    Ummm... the docs do not say anything but what's wrong with experimenting? Feed it broken data, see how it reacts. My bet is either it raises an exception or returns null (maybe `default(T)` to handle structs). In the latter case you don't need to do anything, if it raises exception `try` and return `default()`. – luk32 Mar 30 '15 at 03:34
  • 1
    I don't want to use try catch. Currently I implemented like that but looking to find a way to verify the string before start to deserialize object – Peyman Mar 30 '15 at 05:39
  • @Peymann, I added your comment into the question body, hope no one more is confused why `try catch` option is not considered. – Alexander Stepaniuk Mar 30 '15 at 08:20
  • 1
    Why don't you want to use `try-catch`? Why do you want to parse the JSON before you parse it? It may also be possible for the JSON to be valid, but not deserializable to `TObject` for many reasons. Just use exceptions to handle invalid input, or explain exactly why you don't want to use `try-catch`. – CodeCaster Mar 30 '15 at 08:23
  • @CodeCaster. Because it leads to exception-driven execution flow. There is no need to parse json twice to perform eceptionless deserialization. Look at `TryParse` pattern which is often used in .Net. It doesn't raise an exception neither performs parse twice. Something similar theoretically could be in json.net. Not sure it actually is though. – Alexander Stepaniuk Mar 30 '15 at 09:14
  • 2
    @Alexander sure, but I'm asking OP. Whether invalid JSON is an exception depends on the use case, and a `Try...` method is very likely to swallow the exception internally anyway. As a user, you maybe want to see the actual exception instead of `false` or `null` checking. If it's only input validation, OP [could use Json Schema](http://stackoverflow.com/questions/19544183/validate-json-against-json-schema-c-sharp), but JSON that's valid according to a schema can still fail, for example when it doesn't map to the target class. – CodeCaster Mar 30 '15 at 09:52
  • possible duplicate of [Deserialize json in a "TryParse" way](http://stackoverflow.com/questions/23906220/deserialize-json-in-a-tryparse-way) – Brian Rogers Mar 30 '15 at 14:13
  • 4
    @CodeCaster Actually classes that support `TryAction` idioms do it the other way around. `Action` uses `TryAction` internally and if it fails it raises an exception. The thing is to avoid exception in execution path because it costs, so using one additional `if` to check if we should throw is not so painful, and execution path would get messed anyways. Hiding exception in `Try` would defeat it main purpose which is not to change semantics, but to avoid `try...catch` in execution path. Anyways, OP software of choice doesn't support it, so they need to workaround. – luk32 Mar 30 '15 at 15:11

3 Answers3

18

There is no TryParse in Json.Net as of the current release. If you don't have a known schema to validate against, and you don't want to use try...catch then your only other option that I can see is to attach an error handler to the serializer and use that as a means of detecting and/or handling errors. See "Error Handling" in the documentation.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
16
    private static bool TryParseJSON(string json, out JObject jObject)
    {
        try
        {
            jObject = JObject.Parse(json);
            return true;
        }
        catch
        {
            jObject = null;
            return false;
        }
    }

worked just fine for my scenario

jjxtra
  • 20,415
  • 16
  • 100
  • 140
hngr18
  • 817
  • 10
  • 13
0

This thread implements a decent TryParse using the latest package from Newtonsoft.Json.Schema.