有没有办法反序列化无效的json?
例如,下一个JSON反序列化将失败并显示JsonReaderException
{
'sessionId': 's0j1',
'commandId': 19,
'options': invalidValue // invalid value
}
因为options
属性值无效。
即使sessionId
值无效,有没有很好的方法可以获得commandId
和options
值?
我知道在反序列化过程中可以处理错误(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
。
答案 0 :(得分:2)
您可以使用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
阻止JsonReaderException
reader.Read()