newtonsoft json 역 직렬화 오류 처리 : 부분 역 직렬화

ackacky.bashmachckin

잘못된 json을 역 직렬화하는 방법이 있습니까?

예를 들어 다음 JSON 역 직렬화는 다음과 함께 실패합니다. JsonReaderException

{
 'sessionId': 's0j1',
 'commandId': 19,
 'options': invalidValue // invalid value
}

options속성 값이 유효하지 않기 때문 입니다.

얻을 수있는 좋은 방법이 있나요 sessionIdcommandId경우에도 값 options값이 유효하지 않습니다?

deserialization 중에 오류를 처리 할 수 ​​있다는 것을 알고 있습니다 ( http://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm ).

var json = "{'sessionId': 's0j1', 'commandId': 19, 'options': invalidValue}"; 

var settings = new JsonSerializerSettings
{
    Error = delegate(object sender, ErrorEventArgs args)
    {
      args.ErrorContext.Handled = true;
    }
});
var result = JsonConvert.DeserializeObject(json, settings);

비트 결과는 result = null.

미하일 툴 루바 예프

으로 할 수 있습니다 JsonReader.

예제 코드 :

var result = new Dictionary<string, object>();

using (var reader = new JsonTextReader(new StringReader(yourJsonString)))
{
    var lastProp = string.Empty;
    try
    {
        while (reader.Read())
        {
            if (reader.TokenType == JsonToken.PropertyName)
            {
                lastProp = reader.Value.ToString();
            }

            if (reader.TokenType == JsonToken.Integer || 
                reader.TokenType == JsonToken.String)
            {
                result.Add(lastProp, reader.Value);
            }
        }
    }

    catch(JsonReaderException jre)
    {
        //do anything what you want with exception
    }
}

참고가 있다고 try..catch할 때 블록으로 JsonReader잘못된 문자를 충족이 발생 JsonReaderExceptionreader.Read()

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사