Ignore parsing errors during JSON.NET data parsing

前端 未结 3 1514
无人共我
无人共我 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: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 _roles;
    
      public string Name { get; set; }
      public int Age { get; set; }
    
      public List 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

提交回复
热议问题