Home >Backend Development >C++ >How Can I Efficiently Read and Parse Large JSON Files in C#?

How Can I Efficiently Read and Parse Large JSON Files in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-11 10:26:44944browse

How Can I Efficiently Read and Parse Large JSON Files in C#?

C# efficiently reads and parses large JSON files

When processing large JSON files, efficient reading and parsing is crucial to avoid program crashes or memory overflows. It is recommended to use the JSON.NET library to optimize this process.

Using JSON.NET

JSON.NET provides powerful classes and methods to process JSON data in C#. Here's how to use it to read and parse a large JSON file into an array:

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

You can easily deserialize a JSON string into a list of objects by creating a class corresponding to the JSON structure.

Extract specific data

To extract only the required data (e.g. "vcc" value), you can access the object's properties after deserialization. For example:

<code class="language-csharp">foreach (var item in items)
{
    Console.WriteLine(item.vcc);
}</code>

Dynamic Deserialization

You can even access JSON data dynamically without creating a class. Using the dynamic keyword, you can deserialize a JSON string into a dynamic object:

<code class="language-csharp">dynamic array = JsonConvert.DeserializeObject(json);
foreach (var item in array)
{
    Console.WriteLine("{0} {1}", item.temp, item.vcc);
}</code>

This method allows you to access JSON properties using the property name (a string).

The above is the detailed content of How Can I Efficiently Read and Parse Large JSON Files in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn