Deserialize json in a “TryParse” way

后端 未结 6 642
走了就别回头了
走了就别回头了 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条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 09:30

    Just to provide an example of the try/catch approach (it may be useful to somebody).

    public static bool TryParseJson(this string obj, out T result)
    {
        try
        {
            // Validate missing fields of object
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.MissingMemberHandling = MissingMemberHandling.Error;
    
            result = JsonConvert.DeserializeObject(obj, settings);
            return true;
        }
        catch (Exception)
        {
            result = default(T);
            return false;
        }
    }
    

    Then, it can be used like this:

    var result = default(MyObject);
    bool isValidObject = jsonString.TryParseJson(out result);
    
    if(isValidObject)
    {
        // Do something
    }
    

提交回复
热议问题