Skip to content

JsonHelper

shmellyorc edited this page Sep 12, 2026 · 1 revision

JsonHelper

JsonHelper adds small, type-safe helpers around System.Text.Json.JsonElement.

It is especially useful when reading optional properties where a missing or mismatched value should fall back to a default.

GetPropertyOrDefault

using System.Text.Json;

using var document =
    JsonDocument.Parse(json);

JsonElement root =
    document.RootElement;

string name =
    root.GetPropertyOrDefault(
        "name",
        "Unknown");

int health =
    root.GetPropertyOrDefault(
        "health",
        1);

bool boss =
    root.GetPropertyOrDefault(
        "boss",
        false);

Missing values return the supplied default:

int mana =
    root.GetPropertyOrDefault(
        "mana",
        0);

GetElementOrDefault

Use GetElementOrDefault when you already have the element itself:

JsonElement value =
    root.GetProperty("health");

int health =
    value.GetElementOrDefault(0);

Supported Public Value Types

The helper currently supports common primitives including:

  • string
  • bool
  • signed/unsigned integer types
  • float
  • double
  • decimal
  • DateTime
  • DateTimeOffset
  • Guid
  • enums

Unsupported generic types throw an ArgumentException rather than silently guessing how to deserialize them.

For larger object graphs, use normal System.Text.Json serialization/deserialization.

Enums

For JSON like:

{
    "difficulty": "Hard"
}

you can use:

Difficulty difficulty =
    root.GetPropertyOrDefault(
        "difficulty",
        Difficulty.Normal);

Numeric enum values are also accepted when the value is defined by the enum.

LDtk

VOID also uses JsonHelper internally while converting LDtk field instances into its typed LDtk setting objects.

The LDtk-specific conversion methods are internal; normal game code usually accesses the resulting settings through the public LDtk APIs instead.

See LDtk Settings.


Back to Home

Clone this wiki locally