Efficiently parse medium and large JSON files in C#: Detailed explanation of Json.NET method
When processing large JSON files in C#, loading them directly into an array may encounter performance bottlenecks. This article will introduce an efficient solution using the Json.NET library.
Json.NET is a popular JSON parsing library in C#. It provides a convenient and efficient way to read and parse JSON data.
The following example demonstrates how to load a large JSON file into List<Item>
using Json.NET:
<code class="language-csharp">public void LoadJson() { using (StreamReader r = new StreamReader("file.json")) { string json = r.ReadToEnd(); List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json); } } public class Item { public int millis; public string stamp; public DateTime datetime; public string light; public float temp; public float vcc; }</code>
This code first reads the JSON file into a json
string and then uses JsonConvert.DeserializeObject
to deserialize it into List<Item>
. Each element in the list represents an object whose properties correspond to JSON nodes.
No need to create a custom class, Json.NET can also dynamically obtain JSON data values. An example is as follows:
<code class="language-csharp">dynamic array = JsonConvert.DeserializeObject(json); foreach (var item in array) { Console.WriteLine("{0} {1}", item.temp, item.vcc); }</code>
Here, array
a variable is a dynamic object that allows access to its properties without type checking. This approach is more convenient if you don't need to store the data in a specific object.
The above is the detailed content of How Can Json.NET Efficiently Parse Large JSON Files in C#?. For more information, please follow other related articles on the PHP Chinese website!