System.Text.Json is a modern built-in alternative to Newtonsoft libraries.
using System.Text.Json;private static JsonDocument RequestJson(string url) => RequestJsonAsync(url).Result;private static async Task<JsonDocument> RequestJsonAsync(string url)
{
using HttpClient client = new();
using HttpResponseMessage response = await client.GetAsync(url);
using HttpContent content = response.Content;
string json = await content.ReadAsStringAsync();
return JsonDocument.Parse(json);
}using MemoryStream stream = new();
JsonWriterOptions options = new() { Indented = true };
using Utf8JsonWriter writer = new(stream, options);
writer.WriteStartObject();
writer.WriteNumber("simple value", 123);
writer.WriteStartArray("more values");
for (int i = 0; i < 10; i++)
{
writer.WriteStartObject();
writer.WriteString("alpha", $"asdf{i}");
writer.WriteNumber("beta", i);
writer.WriteEndObject();
}
writer.WriteEndArray();
writer.WriteEndObject();
writer.Flush();
string json = Encoding.UTF8.GetString(stream.ToArray());using JsonDocument document = JsonDocument.Parse(File.ReadAllText(JSON_FILE));
string version = document.RootElement.GetProperty("version").GetString();
string generated = document.RootElement.GetProperty("generated").GetString();
foreach (JsonElement recipeElement in document.RootElement.GetProperty("recipes").EnumerateArray())
{
string id = recipeElement.GetProperty("id").GetString();
string category = recipeElement.GetProperty("category").GetString();
string title = recipeElement.GetProperty("title").GetString();
string description = recipeElement.GetProperty("description").GetString();
string code = recipeElement.GetProperty("code").GetString();
}using (JsonDocument document = JsonDocument.Parse(jsonString))
{
double temperatureC = document.RootElement.GetProperty("temperatureC").GetDouble();
List<Ion> ions = new List<Ion>();
foreach (JsonElement element in document.RootElement.GetProperty("ions").EnumerateArray())
{
string name = element.GetProperty("name").GetString();
int charge = element.GetProperty("charge").GetInt32();
double conductivity = element.GetProperty("conductivity").GetDouble();
}
};Serializable objects are POCOs that:
- Have auto-properties
- Have a parameterless constructor
class Life
{
public string Name { get; set; }
public int Age { get; set; }
public List<string> Interests { get; set; } = new List<string>();
}// instantiate an object
Life myLife = new Life() { Name = "Scott", Age = 35 };
myLife.Interests.Add("science");
myLife.Interests.Add("computers");
myLife.Interests.Add("space");// C# Object to JSON (with option for pretty formatting)
var options = new JsonSerializerOptions() { WriteIndented = true };
string json = JsonSerializer.Serialize(myLife, options);
Console.WriteLine(json);// JSON to C# object
Life myNewLife = JsonSerializer.Deserialize<Life>(json);
Console.WriteLine(myNewLife.Name + " likes " + string.Join(" and ", myNewLife.Interests));// convert an ugly document to a pretty one
JsonDocument document = JsonDocument.Parse(jsonString);
using var stream = new MemoryStream();
var options = new JsonWriterOptions() { Indented = true };
using var writer = new Utf8JsonWriter(stream, options);
document.WriteTo(writer);
writer.Flush();
string jsonPretty = Encoding.UTF8.GetString(stream.ToArray());