Skip to content

Models: Serialization ​

Introduction ​

When you build an API, models are converted to JSON. DotBlaze uses System.Text.Json with web defaults (camelCase property names) and adds Eloquent's $hidden, $visible, and $appends as attributes:

EloquentDotBlaze
$hidden[Hidden]
$visible[Visible]
$appends[Appends]
toJson()ToJson()

Serializing Models ​

Serializing to JSON ​

ToJson serializes a model:

csharp
var author = await Author.Create(new { Name = "Ali", Password = "secret" });

return author.ToJson();
// {"id":1,"name":"Ali","settings":{"theme":"light"},"isActive":true,...,"books":[],"display":"Ali (0)"}

Returning Models From Controllers ​

MVC's JSON output uses the same rules, so returning models (or collections and paginators of models) from a controller just works:

csharp
public IActionResult Show(Post post) => Json(post);

public async Task<IActionResult> Index() => Json(await Post.Scope(Post.Latest).Get());

Relationships ​

Loaded relationships are included under their property names. Relationships that were not loaded appear as null or as an empty array. Reference cycles (a post's user whose posts include that post) are cut off automatically instead of throwing.

Hiding Attributes From JSON ​

Mark properties that must never leave the server, such as password hashes, with [Hidden]:

csharp
public class User : Model<User>
{
    public long Id { get; set; }
    [Fillable] public string Name { get; set; } = "";
    [Fillable, Hidden, Cast(typeof(Hashed))] public string Password { get; set; } = "";
}

Alternatively, list what is allowed: once any property has [Visible], only properties with [Visible] are serialized:

csharp
public class User : Model<User>
{
    [Visible] public long Id { get; set; }
    [Visible] public string Name { get; set; } = "";
    public string Email { get; set; } = "";   // not serialized
}

[Hidden] wins over [Visible] when a property has both.

Appending Values to JSON ​

Computed, get-only properties (accessors) are left out of the JSON by default. Add [Appends] to include one:

csharp
public class Author : Model<Author>
{
    [Fillable] public string Name { get; set; } = "";
    public List<Book> Books { get; set; } = [];

    [Appends] public string Display => $"{Name} ({Books.Count})";   // serialized as "display"
    public string NotAppended => Name.ToUpperInvariant();            // not serialized
}

Appended properties are computed at serialization time, so load any relationship they use first.

Per-Instance Serialization ​

Override the model defaults for one instance without changing other models of the same type:

csharp
user.MakeHidden("Email");
user.MakeVisible("Password"); // explicitly reveal a [Hidden] property for this response
post.Append("Summary");      // include a public computed property
return user.ToJson();

These methods return the model for chaining. Names accept property casing or snake_case. MakeVisible removes a runtime hide and permits an attribute hidden by [Hidden]; MakeHidden wins until it is explicitly made visible again. A [Visible] allow-list still applies, with names passed to MakeVisible added to it. [JsonIgnore] remains effective.

Append validates that the property exists; appended fields still obey visibility rules. Relationship aggregates and selected pivot data are serialized as additional attributes and obey MakeHidden/MakeVisible too. The same per-instance rules apply to MVC JSON output and ModelJson.Options.

Using the Rules Elsewhere ​

ModelJson.Options is the JsonSerializerOptions instance ToJson uses. Pass it to JsonSerializer yourself, or apply the rules to your own options with ModelJson.Configure(options):

csharp
var json = JsonSerializer.Serialize(await Post.All(), ModelJson.Options);

NOTE

These rules only affect JSON output. Queued jobs and events serialize models differently: they store just the model's id and fetch the model again when the job runs, see Queues.

Complete Example: Verify Hidden Fields ​

Use the template's User and the Blog test project. No database is needed to verify serialization of an unsaved model:

csharp
// Blog.Tests/SerializationTest.cs
using System.Text.Json;
using Blog.Models;
using Xunit;

namespace Blog.Tests;

public class SerializationTest
{
    [Fact]
    public void Password_and_two_factor_secrets_are_not_in_json()
    {
        var user = new User
        {
            Name = "Ada", Email = "ada@example.test", Password = "private-hash",
            TwoFactorSecret = "private-secret", RememberToken = "private-token",
        };
        using var json = JsonDocument.Parse(user.ToJson());
        Assert.Equal("Ada", json.RootElement.GetProperty("name").GetString());
        Assert.False(json.RootElement.TryGetProperty("password", out _));
        Assert.False(json.RootElement.TryGetProperty("twoFactorSecret", out _));
        Assert.False(json.RootElement.TryGetProperty("rememberToken", out _));
    }
}

Run dotnet test Blog.Tests --filter FullyQualifiedName~SerializationTest. Expected: one passing test. Inspect property names rather than searching the JSON string for a password value. MakeVisible("Password") overrides this protection for that instance; it is an explicit capability, not a normal API-response pattern.