简体   繁体   English

newtonsoft json反序列化错误处理:部分反序列化

[英]newtonsoft json deserialization error handling: partial deserialization

Is there way to deserialize invalid json? 有没有办法反序列化无效的json?

For example, next JSON deserialization will fail with JsonReaderException 例如,下一个JSON反序列化将因JsonReaderException而失败

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

because options property value is invalid. 因为options属性值无效。

Is there a nice way to get sessionId and commandId values even if options value is invalid? 即使options值无效,有没有一种很好的方法来获取sessionIdcommandId值?

I know it's possible to handle errors during deserialization ( http://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm ) 我知道在反序列化过程中可以处理错误( 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);

Bit it will result in result = null . 它会导致result = null

You can do it with JsonReader . 你可以用JsonReader做到这JsonReader

Example code: 示例代码:

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

Note, that there is try..catch block as when JsonReader meets invalid character it throws JsonReaderException on reader.Read() 注意,有try..catch块,因为当JsonReader遇到无效字符时,它会在reader.Read()上抛出JsonReaderException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM