1. Preparation
Processing JSON files in C# is usually done by third-party libraries, such as(also known as). It provides rich APIs for serialization and deserialization of JSON. If you are using newer .NET Core or .NET 6 and later, you can also choose to use the built-in onelibrary. Here we will take it as an example because it is widely used in the .NET ecosystem and has mature functions.
First, make sure you have installed the library in your project through the NuGet package manager. If you have not installed it, open Tools -> NuGet Package Manager -> NuGet Packages for Manage Solutions in Visual Studio, search and install ".
2. Read JSON files
Step 1: Introduce the necessary namespace
Csharp
using System; using ; using ;
Step 2: Write code to read JSON files
Suppose we have a name calledThe file containing a JSON object representing user information:
Json
{ "Name": "John Doe", "Age": 30, "IsAdmin": false, "Skills": ["C#", "JavaScript", "SQL"] }
We can read and deserialize it into a C# object using the following code:
Csharp
// Define a C# kindpublic class User corresponding to the JSON structure{ public string Name { get; set; } public int Age { get; set; } public bool IsAdmin { get; set; } public string[] Skills { get; set; } } public static User ReadJsonFile() { // JSON file path string filePath = @"path\to\"; try { // Open and read the file content using (StreamReader fileReader = new StreamReader(filePath)) { // Get JSON string from file string jsonContent = (); // Use deserialization of JSON string as User object User user = <User>(jsonContent); return user; } } catch (FileNotFoundException ex) { ($"Error: document {filePath} not found。"); throw; } catch (Exception ex) { ($"Error: Read or parseJSONdocument时发生错误。{}"); throw; } }
Code comment description
-
User
The class defines properties that match the JSON structure so that JSON data is mapped to the corresponding C# object when deserialized. -
ReadJsonFile
Method:- First specify the path to the JSON file.
- use
StreamReader
Open and read the file contents into a string variablejsonContent
middle. - Call
<User>
Method, convert JSON string toUser
An instance of type. - use
try-catch
Statements catch possible exceptions, such as files not found or errors that occur during parsing, and handle them appropriately.
3. Write to JSON file
Step 1: Make sure that the required namespace has been introduced (same as the read section)
Csharp
using System; using ; using ;
Step 2: Write code to write JSON file
Suppose we have oneUser
object, want to serialize it into a JSON string and save it to a nameIn the file:
Csharp
public static void WriteJsonFile(User user) { // JSON file output path string outputPath = @"path\to\"; try { // Serialize the User object into a JSON string string jsonOutput = (user, ); // Write JSON string to file using (StreamWriter fileWriter = new StreamWriter(outputPath)) { (jsonOutput); } ("User data successfully written to JSON file."); } catch (Exception ex) { ($"Error: WriteJSONAn error occurred while file。{}"); throw; } }
Code comment description
-
WriteJsonFile
Method to accept oneUser
Object as parameter. - use
The method will be passed in
User
Serialize objects into formatted JSON strings (parameters make it readable).
- Create a
StreamWriter
object, specifiedoutputPath
Open the file and write the JSON string to the file. - Use the same
try-catch
Statements catch and handle possible exceptions.
Summarize
The above code shows how to use C# to read and write JSON files. By defining a C# class that matches the JSON structure, you can easily convert JSON data to the object model in your application. In practical applications, you can just replace or extend the classes and methods in these examples to adapt to your specific business needs. Be sure to pay attention to the correctness of file paths and permissions for file operations, as well as to adopt appropriate recovery or notification mechanisms when handling exceptions.
This is the article about detailed code examples and comment analysis of C# reading and writing JSON files. For more related contents of C# reading and writing JSON files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!