Introduction
When a developer needs to view the instance of a model at runtime, an easy way is to display the details as JSON. Here, learn how to do this was formatted json.
Below shows the result of colorized JSON using the NuGet package Spectre.Console.Json with formatting of JSON in the Program.cs
builder.Services.Configure<JsonOptions>(options =>
{
options.SerializerOptions.WriteIndented = true;
});
Class project SpectreConsoleJsonLibrary
Provides a method to render JSON colorized rather than placing the code in the front-end project, as this code is only needed for the development environment.
Sample
Inject using a primary constructor JsonOptions
public class ViewContactModel(
Context context,
IOptions<JsonOptions> jsonOptions) : PageModel
{
. . .
Add the following method to prevent runtime exceptions as per gets an object that indicates whether an object is ignored when a reference cycle is detected during serialization.
private JsonSerializerOptions JsonSerializerOptions() => new(jsonOptions.Value.SerializerOptions)
{
ReferenceHandler = ReferenceHandler.IgnoreCycles
};
Display the contact as JSON.
public Contact Contact { get; set; } = null!;
public async Task<IActionResult> OnGetAsync(int id)
{
var contact = await ContactOperations.GetByIdentifier(context, id);
if (contact is not null)
{
Contact = contact;
var json = JsonSerializer.Serialize(Contact, JsonSerializerOptions());
Utilities.DisplayJsonConsole(json, "Contact");
return Page();
}
return NotFound();
}
To ensure the JSON code above does not work outside of development, add IWebHostEnvironment env to the page constructor.
public class ViewContactModel(
Context context,
IOptions<JsonOptions> jsonOptions,
IWebHostEnvironment env) : PageModel
. . .
Next, modify OnGet to only display the JSON if in the development environment.
public async Task<IActionResult> OnGetAsync(int id)
{
var contact = await ContactOperations.GetByIdentifier(context, id);
if (contact is not null)
{
Contact = contact;
if (env.IsDevelopment())
{
var json = JsonSerializer.Serialize(Contact, JsonSerializerOptions());
Utilities.DisplayJsonConsole(json, "Contact");
}
return Page();
}
return NotFound();
}
Source code
Front-end project JSON Methods EF Core project
Running provided sample
As provided the database is expected under (localdb)\\MSSQLLocalDB
To create the database and populate follow these instructions.

Top comments (0)