How to update JSON value in C#

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is widely used for data storage and transmission. It offers a simple and readable structure for representing data objects and collections. In this article, we will explore how to update JSON using Microsoft’s new API for JSON, System.Text.Json.

Introducing System.Text.Json

System.Text.Json is a powerful library provided by Microsoft that enables easy parsing and serialization of JSON data in C#. It offers classes and methods to efficiently work with JSON text, allowing developers to seamlessly convert JSON to C# objects and vice versa. This library replaces the need for third-party JSON parsing and serialization libraries in .NET applications.

Updating JSON with System.Text.Json

To demonstrate how to update JSON using System.Text.Json, let’s consider a JSON document representing a collection of people with their information and a list of friends. We want to filter out individuals who have more than two friends and obtain the updated JSON document.

var jsonArray = @"[
	{
		""firstName"":""John"",
		""lastName"":""Doe"",
		""Age"":35,
		""friends"":[""Joe""]
	},
	{
		""firstName"":""Jane"",
		""lastName"":""Doe"",
		""Age"":42,
		""friends"":[""Joe"",""Joy"",""Xi""]
	},
	{
		""firstName"":""Bill"",
		""lastName"":""Gates"",
		""Age"":46,
		""friends"":[""Sara"",""Joe""]
	}
]";

Output

[
  {
    "firstName": "Jane",
    "lastName": "Doe",
    "Age": 42,
    "friends": [
      "Joe",
      "Joy",
      "Xi"
    ]
  },
  {
    "firstName": "Bill",
    "lastName": "Gates",
    "Age": 46,
    "friends": [
      "Sara",
      "Joe"
    ]
  }

To achieve the desired result, we can use the System.Text.Json library as follows:

void Main()
{
	var jsonArray = @"[
	{
		""firstName"":""John"",
		""lastName"":""Doe"",
		""Age"":35,
		""friends"":[""Joe""]
	},
	{
		""firstName"":""Jane"",
		""lastName"":""Doe"",
		""Age"":42,
		""friends"":[""Joe"",""Joy"",""Xi""]
	},
	{
		""firstName"":""Bill"",
		""lastName"":""Gates"",
		""Age"":46,
		""friends"":[""Sara"",""Joe""]
	}
]";

	var options = new JsonWriterOptions { Indented = true };
	using JsonDocument document = JsonDocument.Parse(jsonArray);

	using (var stream = new MemoryStream())
	{
		using (var writer = new Utf8JsonWriter(stream, options))
		{
			writer.WriteStartArray();
			foreach (var person in document.RootElement.EnumerateArray())
			{
				int friendCount = person.GetProperty("friends").GetArrayLength();
				if (friendCount >= 2)
					person.WriteTo(writer);
			}


		}
		stream.Position = 0;
		Console.WriteLine(new StreamReader(stream).ReadToEnd());

	}

}

Let’s break down the program step by step:

  1. We first parse the JSON document using JsonDocument.
  2. Next, we create a MemoryStream to store the updated JSON document.
  3. Using Utf8JsonWriter, we loop through the JSON array and filter out individuals who have more than two friends.
  4. The filtered JSON data is written to the Utf8JsonWriter instance.
  5. Finally, we reset the stream position, read the updated JSON from the stream, and display it in the console.

The introduction of System.Text.Json has simplified the process of updating JSON data in C#. It eliminates the need for external libraries and provides a performant and intuitive way to work with JSON.

Before the introduction of this library, developers often relied on third-party libraries or custom implementations for JSON manipulation. This could lead to dependency management issues, performance concerns, and inconsistent JSON handling across projects. With System.Text.Json, Microsoft has provided a standardized and efficient solution within the .NET ecosystem.

 Additional Possibilities

System.Text.Json offers a wide range of functionalities for working with JSON. Here are a few additional scenarios you can explore:

  • Deserializing JSON into C# objects: System.Text.Json provides methods to deserialize JSON into strongly typed C# objects, enabling easy access to the data and leveraging the benefits of static typing.
  • Serializing C# objects to JSON: You can use System.Text.Json to serialize C# objects into JSON format effortlessly. This allows you to store or transmit data in a JSON-based format.
  • Handling complex JSON structures: The library supports handling complex JSON structures with nested objects and arrays, making it suitable for a variety of JSON data scenarios.

 Conclusion

System.Text.Json is a powerful API for working with JSON in C#, providing a standardized and efficient way to parse, manipulate, and serialize JSON data. In this article, we explored how to update JSON using System.Text.Json, simplifying the process of filtering and modifying JSON objects. By leveraging this library, developers can efficiently handle JSON data within the .NET ecosystem, eliminating the need for external dependencies and ensuring consistent JSON processing across their projects.

The MemoryStream class is used to create an in-memory stream from an array of bytes or a string. The stream can be written to using the Write or AppendTo methods, it can be read from using Read or Seek methods, and it can be cleared using the Clear method.

إرسال تعليق

Please do not post any spam link in the comment box😊

أحدث أقدم

Blog ads

CodeGuru