Program Club

JSON.NET 데이터 구문 분석 중 구문 분석 오류 무시

proclub 2021. 1. 7. 08:16
반응형

JSON.NET 데이터 구문 분석 중 구문 분석 오류 무시


미리 정의 된 데이터 구조가있는 개체가 있습니다.

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

그리고 JSON은

{ "Id": "123", "Enabled": true, "Age": 23 }

JSON 오류를 긍정적 인 방식으로 처리하고 싶고 서버가 정의 된 데이터 유형에 대해 예상치 못한 값을 반환 할 때마다 무시하고 기본값이 설정 (null)되기를 원합니다.

지금 JSON이 부분적으로 유효하지 않은 경우 JSON 판독기 예외가 발생합니다.

{ "Id": "123", "Enabled": "NotABoolValue", "Age": 23 }

그리고 나는 어떤 물건도 얻지 못합니다. 내가 원하는 것은 객체를 얻는 것입니다.

new A() { Id = "123", Enabled = null, Age = 23 }

가능한 경우 파싱 경고. JSON.NET으로 수행 할 수 있습니까?


역 직렬화 오류를 처리하려면 다음 코드를 사용하십시오.

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

HandleDeserializationError다음 방법은 어디에 있습니까?

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

HandleDeserializationErrorjson으로 문자열에 오류가있는만큼 여러 번 호출됩니다. 오류를 일으키는 속성은 초기화되지 않습니다.


Ilija의 솔루션과 동일하지만 게 으르거나 서두르는 사람들을위한 oneliner (크레딧이 그에게갑니다)

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

더 짧게 만들기 위해 Jam에 대한 소품 =)


다른 방법이 있습니다. 예를 들어, newton json을 사용하고 deseralization 및 seralization을 수행하는 nuget 패키지를 사용하는 경우. 패키지가 오류를 처리하지 않는 경우이 문제가 발생할 수 있습니다. 위의 솔루션을 사용할 수 없습니다. 개체 수준에서 처리해야합니다. 여기에 OnErrorAttribute가 유용합니다. 따라서 아래 코드는 모든 속성에 대한 오류를 포착하므로 OnError 함수 내에서 수정하고 기본값을 할당 할 수도 있습니다.

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;
  }
}

참조 https://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm를

참조 URL : https://stackoverflow.com/questions/26107656/ignore-parsing-errors-during-json-net-data-parsing

반응형