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

How to Efficiently Read and Parse JSON Files in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-11 10:15:43491browse

How to Efficiently Read and Parse JSON Files in C#?

C# efficiently reads and parses JSON files

In C#, the process of reading and parsing JSON files can be simplified by using third-party libraries. It is recommended to use the Json.NET library.

Use the JsonTextReader class to read JSON files into an array. However, for large files, this approach may run into problems due to memory consumption.

A better way is to use the JsonConvert class in Json.NET:

<code class="language-csharp">using Newtonsoft.Json;

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 will deserialize a JSON string into a list of Item objects. The individual values ​​can then be accessed as needed.

For example, to extract a specific value without creating a custom class, you can use the following method:

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

This dynamic approach provides a flexible way to handle specific properties of JSON objects without explicitly defining a class structure.

The above is the detailed content of How to Efficiently Read and Parse 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