Skip to content

@Json Tag

William David Cossey edited this page Jun 7, 2020 · 4 revisions
Required Version
0.2.x

RazorEngineCore.Extensions supports @Json tags using a custom RazorEngineCoreJsonWriter class.

RazorEngineCoreJsonWriter like AspNetCore uses System.Text.Json.JsonSerializer for JSON serialization, this is to ensure the same behaviour as Razor Pages in AspNetCore and to reduce dependencies (w/o the need for Newtonsoft.Json).

Basic Sample

Input:

@Json(new { Title = "My Title", Description = "This is a description", Null = (object)null })   

Output:

{"Title":"My Title","Description":"This is a description","Null":null}

Configuration

As the @Json writer is not injected via IoC configuration is different to that of a standard .Net Core application.

Defaults

WriteIndented : false;

AllowTrailingCommas : false;

IgnoreNullValues : false;

MaxDepth : 64;

DefaultBufferSize : 16 * 1024; //16KB

IgnoreReadOnlyProperties : false;

PropertyNameCaseInsensitive : false;

Global Configuration:

You can configure the @Json settings for the entire scope of your template.

@inherits RazorEngineCore.RazorEngineCorePageModel

@{
    Json.WriteIndented(true)
        .AllowTrailingCommas(true)
        .IgnoreNullValues(false)
        .MaxDepth(64)
        .DefaultBufferSize(16 * 1024)
        .IgnoreReadOnlyProperties(false)
        .PropertyNameCaseInsensitive(false);
}

In-Line Configuration:

Alternatively you can use in-line settings, these will inherit the Global/Defaults unless specified in the parameters.

@Json.Serialize(new { Title = "My Title" }, 
    allowTrailingCommas: false,
    defaultBufferSize: 16 * 1024,
    ignoreNullValue: false,
    ignoreReadOnlyProperties: true,
    maxDepth: 64,
    propertyNameCaseInsensitive: true,
    writeIndented: false)

Mixed Configuration:

@json configuration can also be mixed between global and in-line.

@inherits RazorEngineCore.RazorEngineCorePageModel

@{
    var jsonObject = new { Title = "My Title", Description = "This is a description", Null = (object)null };

    Json.WriteIndented(true)
        .AllowTrailingCommas(false)
        .IgnoreNullValues(true)
        .MaxDepth(64)
        .DefaultBufferSize(8 * 1024)
        .IgnoreReadOnlyProperties(false)
        .PropertyNameCaseInsensitive(true);
}

<code>
    @Json.Serialize(jsonObject, 
        allowTrailingCommas: false,
        ignoreNullValue: true,
        maxDepth: 32,
        writeIndented: true)
</code>

<code>
    @Json.Serialize(jsonObject, 
        defaultBufferSize: 4 * 1024,
        ignoreReadOnlyProperties: true,
        propertyNameCaseInsensitive: false,
        writeIndented: false)
</code>
Clone this wiki locally