Optimized JSON handling is increasingly important in developing programs. New versions of .NET include the System.Text.Json
namespace, which helps matters.
To parse in JSON, we need to write special, custom classes that match the JSON data we are parsing. These classes are then populated automatically by .NET.
Reading JSON data is done with the Deserialize()
method. We must first include System.Text.Json
, and we must have a class
that matches the data format.
string
. And the types of the data must also match.using System; using System.Text.Json; public class AnimalData { public int Bird { get; set; } public string Cat { get; set; } } class Program { const string _example = @"{""Bird"":10,""Cat"":""Fuzzy""}"; static void Main() { var result = JsonSerializer.Deserialize<AnimalData>(_example); Console.WriteLine("BIRD JSON: {0}", result.Bird); Console.WriteLine("CAT JSON: {0}", result.Cat); } }BIRD JSON: 10 CAT JSON: Fuzzy
To write JSON from a class
in memory, we must call the Serialize method. We can specify a type parameter to the generic Serialize method.
AnimalData
with 2 properties set, and then writes it to a JSON string
and prints the string
.using System; using System.Text.Json; public class AnimalData { public int Bird { get; set; } public string Cat { get; set; } } class Program { static void Main() { // Create new object with 2 properties. var data = new AnimalData(){ Bird = 20, Cat = "Soft" }; // Call Serialize. var result = JsonSerializer.Serialize<AnimalData>(data); Console.WriteLine("JSON RESULT: {0}", result); } }JSON RESULT: {"Bird":20,"Cat":"Soft"}
List
Often JSON contains lists. We can read JSON text directly into a List
with Deserialize. We place a List
property on a class
with an identifier that matches the JSON key.
List
int
to int[]
.using System; using System.Collections.Generic; using System.Text.Json; class Result { public List<int> Values { get; set; } } class Program { const string _text = @"{""Values"":[10, 20, 30]}"; static void Main() { var result = JsonSerializer.Deserialize<Result>(_text); // Get list property from class. var list = result.Values; Console.WriteLine("RESULT LIST: {0}", string.Join(",", list)); } }RESULT LIST: 10,20,30
Dictionary
We can parse in a Dictionary
from JSON—no special classes are needed. This code does not rely on property names to store JSON key value pairs—it just uses Dictionary
keys.
using System; using System.Collections.Generic; using System.Text.Json; class Program { const string _text = @"{""One"":1,""Two"":2}"; static void Main() { var result = JsonSerializer.Deserialize<Dictionary<string, int>>(_text); // Loop over dictionary from JSON. foreach (var item in result) { Console.WriteLine("ITEM: {0}, {1}", item.Key, item.Value); } } }ITEM: One, 1 ITEM: Two, 2
With an optimized JSON handling library, we can process this convenient text format more easily. We invoke Deserialize and Serialize in our programs.