Keywords: C# | JSON | Newtonsoft.Json | file modification | dynamic type
Abstract: This article explores methods for permanently modifying JSON configuration files in C# applications, focusing on two technical approaches using the Newtonsoft.Json library: the dynamic type and the JObject class. By detailing the complete process of file reading, JSON deserialization, property modification, and serialization back to file, it provides an in-depth analysis of the pros and cons of dynamic versus strongly-typed JSON operations, with practical code examples and best practice recommendations for dynamic configuration management scenarios.
In software development, JSON files are commonly used as configuration files to store application settings and parameters. When modifications to these configurations are needed, developers face the challenge of updating file content safely and efficiently. This article uses C# as an example, combined with the Newtonsoft.Json library, to detail two methods for modifying JSON files: using the dynamic type for quick operations and leveraging the JObject class for more structured access.
Basic Process of JSON File Modification
Modifying a JSON file typically follows these steps: first, read the file content, then deserialize it into an operable data structure, modify the target properties, and finally serialize the modified data back to the file. In C#, Newtonsoft.Json (also known as Json.NET) is a popular library for handling JSON data, offering multiple ways to implement this process.
Quick Modification Using the Dynamic Type
The dynamic type allows runtime dynamic access to JSON object properties without predefining class structures. This method is concise and intuitive, particularly suitable for rapid prototyping or one-off script tasks. The following example code demonstrates how to modify the Password property of the first element in the Bots array within a JSON file:
string json = File.ReadAllText("settings.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
jsonObj["Bots"][0]["Password"] = "new password";
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("settings.json", output);
This code first reads the JSON file content using File.ReadAllText, then deserializes it into a dynamic object via JsonConvert.DeserializeObject. After modifying the property, it uses JsonConvert.SerializeObject to serialize the object into a formatted JSON string and writes it back to the original file. The advantage of the dynamic type is code simplicity, but drawbacks include lack of compile-time type checking and potential runtime errors.
Structured Modification Using the JObject Class
For more complex scenarios or production environments, it is recommended to use the JObject class, which offers stronger type safety and flexible querying capabilities. JObject belongs to the Newtonsoft.Json.Linq namespace and allows access to nested properties via path expressions. The following code demonstrates how to modify JSON values using JObject:
using Newtonsoft.Json.Linq;
string jsonString = File.ReadAllText("myfile.json");
JObject jObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString) as JObject;
JToken jToken = jObject.SelectToken("Bots[0].Password");
jToken.Replace("myNewPassword123");
string updatedJsonString = jObject.ToString();
File.WriteAllText("myfile.json", updatedJsonString);
Here, the SelectToken method uses a JSONPath-like syntax to locate the target property, and the Replace method updates its value. JObject supports modifying various data types, such as strings, integers, and booleans, and handles type conversions automatically. Additionally, the ToString method outputs formatted JSON by default, enhancing readability.
Technical Comparison and Best Practices
The dynamic type is suitable for simple, temporary modification tasks, with minimal code but at the cost of type safety. In contrast, JObject provides a more controlled API, supporting complex queries and error handling, making it better suited for long-term maintenance projects. In practice, developers should choose the appropriate method based on project needs: use dynamic for quick validation or scripts, and prefer JObject or predefined classes for strongly-typed deserialization in enterprise applications.
Regardless of the method chosen, attention should be paid to the safety of file operations, such as handling exceptions for missing files or insufficient permissions, and ensuring backups of original files before modifications to prevent data loss. By effectively utilizing the Newtonsoft.Json library, developers can efficiently manage JSON configuration files, enhancing application flexibility and maintainability.