Recursive AI

Serialize vectors and matrices as JSON in C#

OneMath is a free, open-source deterministic math library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Serialize math values without writing a custom JSON converter.

Terminal
dotnet add package RecursiveAI.OneMath

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using Json = System.Text.Json.JsonSerializer;
using RecursiveAI.OneMath;
 
Console.WriteLine(Json.Serialize(
    new Vector3D(1, 2, 3)));
Console.WriteLine(Json.Serialize(
    new Matrix2x2D(1, 2, 3, 4)));
Text
{"X":1,"Y":2,"Z":3}
{"M11":1,"M12":2,"M21":3,"M22":4}

Unzip the example, then dotnet run.

The full program

The second half optionally uses source-generated metadata for AOT-friendly serialization.

C#
using System.Text.Json;
using System.Text.Json.Serialization;
using RecursiveAI.OneMath;
 
var vector = new Vector3D(1.25, -2.5, 3.75);
var matrix = new Matrix2x2D(1, 2, 3, 4);
string vectorJson = JsonSerializer.Serialize(vector);
string matrixJson = JsonSerializer.Serialize(matrix);
Console.WriteLine(vectorJson);
Console.WriteLine(matrixJson);
Console.WriteLine($"Default vector: {JsonSerializer.Deserialize<Vector3D>(vectorJson) == vector}");
Console.WriteLine($"Default matrix: {JsonSerializer.Deserialize<Matrix2x2D>(matrixJson) == matrix}");
string generatedVector = JsonSerializer.Serialize(vector, MathJson.Default.Vector3D);
string generatedMatrix = JsonSerializer.Serialize(matrix, MathJson.Default.Matrix2x2D);
Console.WriteLine($"Generated vector: {JsonSerializer.Deserialize(generatedVector, MathJson.Default.Vector3D) == vector}");
Console.WriteLine($"Generated matrix: {JsonSerializer.Deserialize(generatedMatrix, MathJson.Default.Matrix2x2D) == matrix}");
try
{
    JsonSerializer.Serialize(Bounds3D.Empty);
}
catch (ArgumentException)
{
    Console.WriteLine("Empty bounds: non-finite numbers rejected");
}
 
[JsonSerializable(typeof(Vector3D))]
[JsonSerializable(typeof(Matrix2x2D))]
internal partial class MathJson : JsonSerializerContext { }

dotnet run prints:

Text
{"X":1.25,"Y":-2.5,"Z":3.75}
{"M11":1,"M12":2,"M21":3,"M22":4}
Default vector: True
Default matrix: True
Generated vector: True
Generated matrix: True
Empty bounds: non-finite numbers rejected

Default JSON serialization throws ArgumentException for non-finite components, including the infinities in Bounds3D.Empty; the full program catches that case.

Variations

Represent empty bounds as JSON null and restore the sentinel:

C#
using System.Text.Json;
using RecursiveAI.OneMath;
 
var box = Bounds3D.Empty;
Bounds3D? payload = box.IsEmpty ? null : box;
string json = JsonSerializer.Serialize(payload);
var restored = JsonSerializer.Deserialize<Bounds3D?>(json)
    ?? Bounds3D.Empty;
Console.WriteLine(json);
Console.WriteLine(restored.IsEmpty);
Text
null
True

The short answer

OneMath vectors and matrices work with System.Text.Json without a custom converter. Call JsonSerializer.Serialize(value) and deserialize to the same concrete type. The component fields carry JsonInclude, and the component constructor carries JsonConstructor. The full program round-trips both a Vector3D and a Matrix2x2D using default options and generated metadata.

This is JSON for fixed-size math values, not a converter for arbitrary multidimensional arrays. The matrix object contains named entries such as M11 and M12; it is not serialized as an array of rows. All sample inputs are literal numbers in the program, so the download needs no external files.

How do you serialize vectors and matrices to JSON in C#?

Pass the value to JsonSerializer.Serialize. A vector becomes an object with its component names, and a matrix becomes an object with its row-and-column field names. The snippet at the top shows the exact compact JSON for both. Deserialization selects the component constructor, rebuilding the immutable value instead of requiring writable component properties.

Microsoft’s serialization guide explains the general serializer behavior. Ordinary fields are ignored by default, but OneMath explicitly annotates its public component fields. You do not need to set IncludeFields = true or introduce a wrapper class just to expose them. Nor do you need to serialize derived values such as vector length alongside the components.

The OneMath’s Evaluation order documentation says public value types read back their components “bit for bit with default options and with source-generated metadata.” Derived members such as QuaternionD.Vector, Vector4D.XYZ and bounds center, size, extents and emptiness are not written. Those values can be computed again from the stored components.

How do you use source generation for JSON serialization?

The full program includes a partial MathJson class derived from JsonSerializerContext, with one JsonSerializable attribute for each math type being serialized. The .NET JSON source generator supplies MathJson.Default.Vector3D and MathJson.Default.Matrix2x2D at build time. Pass that generated type information into both Serialize and Deserialize.

Keep the context declaration with the program or in its own C# file in the same project. The download includes the complete declaration and a .NET 10 project; no additional serialization package is needed. Add an attribute for each additional root type you want the context to support. The example prints separate success checks for default serialization and generated metadata, so it is clear which path ran.

Can JSON represent infinity?

Not with default options. Bounds3D.Empty stores positive infinity in its minimum corner and negative infinity in its maximum corner. These are useful sentinel values for accumulating bounds but are not ordinary JSON numbers. The full program catches the actual serialization exception rather than presenting an empty JSON object as a valid result.

Choose an explicit wire representation for “no bounds.” The variation uses a nullable bounds value: empty becomes JSON null, and deserializing null restores Bounds3D.Empty. This is an application-level choice; it collapses any empty box to the canonical empty sentinel rather than preserving its original corners.

For nonempty bounds, check that your components are finite if the data may come from untrusted calculations or input. IsEmpty describes corner ordering, not a general finite-number check. Likewise, a non-finite vector or matrix is subject to the default serializer’s numeric restrictions even though it has no bounding-box semantics. Avoid silently replacing those values with zero: that changes the math rather than representing the failure.

All onemath recipes