JSON is a lightweight data-interchange format that’s easy for both humans and computers to read and write. It’s based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999.
In this article, I will show you how to update JSON using Microsoft’s new API for JSON named System.Text.Json
The System.Text.Json package provides classes that make it easy to parse JSON text into C# objects (and vice versa). These classes support parsing JSON text generated by any standards-compliant JSON parser or generator, including the JavaScript built-in methods for generating JSON text from arrays and objects.
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""]
}
]";
Let's suppose you want to update the above Json
document where the friends' count is greater than 2 as shown below
[
{
"firstName": "Jane",
"lastName": "Doe",
"Age": 42,
"friends": [
"Joe",
"Joy",
"Xi"
]
},
{
"firstName": "Bill",
"lastName": "Gates",
"Age": 46,
"friends": [
"Sara",
"Joe"
]
}
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 understand the above program line by line
- First I parse the document using
JsonDocument
- Then I created a stream to write the updated document
- After that, I created the instance of
Utf8JsonWriter
(Utf8JsonWriter is a high-performance way to write UTF-8 encoded JSON) - Then I loop the JSON array and check if the friends count is greater than 2 corresponding to Utf8JsonWriter
Here I am using the stream but you can read the JSON data from the file and update the same file with the updated data.
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.