Ignore parsing errors during JSON.NET data parsing

前端 未结 3 1498
无人共我
无人共我 2020-11-30 02:42

I have an object with predefined data structure:

public class A
{
    public string Id {get;set;}
    public bool? Enabled {get;set;}
    public int? Age {ge         


        
相关标签:
3条回答
  • 2020-11-30 03:19

    Same thing as Ilija's solution, but a oneliner for the lazy/on a rush (credit goes to him)

    var settings = new JsonSerializerSettings { Error = (se, ev) => { ev.ErrorContext.Handled = true; } };
    JsonConvert.DeserializeObject<YourType>(yourJsonStringVariable, settings);
    

    Props to Jam for making it even shorter =)

    0 讨论(0)
  • 2020-11-30 03:27

    To be able to handle deserialization errors, use the following code:

    var a = JsonConvert.DeserializeObject<A>("-- JSON STRING --", new JsonSerializerSettings
        {
            Error = HandleDeserializationError
        });
    

    where HandleDeserializationError is the following method:

    public void HandleDeserializationError(object sender, ErrorEventArgs errorArgs)
    {
        var currentError = errorArgs.ErrorContext.Error.Message;
        errorArgs.ErrorContext.Handled = true;
    }
    

    The HandleDeserializationError will be called as many times as there are errors in the json string. The properties that are causing the error will not be initialized.

    0 讨论(0)
  • 2020-11-30 03:39

    There is another way. for example, if you are using a nuget package which uses newton json and does deseralization and seralization for you. You may have this problem if the package is not handling errors. then you cant use the solution above. you need to handle in object level. here becomes OnErrorAttribute useful. So below code will catch any error for any property, you can even modify within the OnError function and assign default values

    public class PersonError
    {
      private List<string> _roles;
    
      public string Name { get; set; }
      public int Age { get; set; }
    
      public List<string> Roles
      {
        get
        {
            if (_roles == null)
            {
                throw new Exception("Roles not loaded!");
            }
    
            return _roles;
        }
        set { _roles = value; }
      }
    
      public string Title { get; set; }
    
      [OnError]
      internal void OnError(StreamingContext context, ErrorContext errorContext)
      {
        errorContext.Handled = true;
      }
    }
    

    see https://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm

    0 讨论(0)
提交回复
热议问题