需要处理大型JSON文件。对于优化内存使用use语法,在执行方法reader.Read()之前,寻找一种检查输入JSON是否有效或输入流是JSON的方法,因为在执行无效的JSON之后,此语法会在此处引发异常。 / p>
例外: Newtonsoft.Json.JsonReaderException:'在解析值h时遇到意外字符。路径”,第0行,位置0。'
HttpClient client = new HttpClient();
using (Stream s = client.GetStreamAsync("http://www.test.com/large.json").Result)
using (StreamReader sr = new StreamReader(s))
using (JsonReader reader = new JsonTextReader(sr))
{
JsonSerializer serializer = new JsonSerializer();
// read the json from a stream
// json size doesn't matter because only a small piece is read at a time from the HTTP request
while (reader.Read())//invalid json throws exception
Person p = serializer.Deserialize<Person>(reader);
}