Deserialize json in a “TryParse” way

后端 未结 6 644
走了就别回头了
走了就别回头了 2020-11-28 09:14

When I send a request to a service (that I do not own), it may respond either with the JSON data requested, or with an error that looks like this:

{
    \"er         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 09:38

    @Victor LG's answer using Newtonsoft is close, but it doesn't technically avoid the a catch as the original poster requested. It just moves it elsewhere. Also, though it creates a settings instance to enable catching missing members, those settings aren't passed to the DeserializeObject call so they are actually ignored.

    Here's a "catch free" version of his extension method that also includes the missing members flag. The key to avoiding the catch is setting the Error property of the settings object to a lambda which then sets a flag to indicate failure and clears the error so it doesn't cause an exception.

     public static bool TryParseJson(this string @this, out T result)
     {
        bool success = true;
        var settings = new JsonSerializerSettings
        {
            Error = (sender, args) => { success = false; args.ErrorContext.Handled = true; },
            MissingMemberHandling = MissingMemberHandling.Error
        };
        result = JsonConvert.DeserializeObject(@this, settings);
        return success;
    }
    

    Here's an example to use it:

    if(value.TryParseJson(out MyType result))
    { 
        // Do something with result…
    }
    

提交回复
热议问题