Files
sbox-public/engine/Sandbox.Engine/Utility/Json/BinaryConvert.cs
Antoine Pilote d28a62c1f3 BinarySerializable (#3725)
Added BlobData API which will serialize as a binary file blob.
> Useful for large data structure

```csharp
class MyBinaryData : BlobData
{
    public override void Serialize( ref Writer writer )
    {
        writer.Stream.Write( 1337 );
    }

    public override void Deserialize( ref Reader reader )
    {
        int val = reader.Stream.Read<int>();
    }
}
```
2026-01-15 05:57:30 -08:00

71 lines
1.7 KiB
C#

using System.Text.Json;
using System.Text.Json.Serialization;
namespace Sandbox;
/// <summary>
/// JSON converter that handles BinaryBlob serialization
/// </summary>
internal class BinaryConvert : JsonConverterFactory
{
public override bool CanConvert( Type typeToConvert )
{
return typeof( BlobData ).IsAssignableFrom( typeToConvert );
}
public override JsonConverter CreateConverter( Type typeToConvert, JsonSerializerOptions options )
{
return (JsonConverter)Activator.CreateInstance(
typeof( BinaryBlobConverter<> ).MakeGenericType( typeToConvert ) );
}
private class BinaryBlobConverter<T> : JsonConverter<T> where T : BlobData
{
public override T Read( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options )
{
// Read the $blob reference
if ( reader.TokenType != JsonTokenType.StartObject )
return null;
Guid? blobGuid = null;
while ( reader.Read() )
{
if ( reader.TokenType == JsonTokenType.EndObject )
break;
if ( reader.TokenType == JsonTokenType.PropertyName )
{
var propertyName = reader.GetString();
reader.Read();
if ( propertyName == "$blob" && reader.TokenType == JsonTokenType.String )
{
if ( Guid.TryParse( reader.GetString(), out var guid ) )
{
blobGuid = guid;
}
}
}
}
if ( blobGuid.HasValue )
{
return BlobDataSerializer.ReadBlob( blobGuid.Value, typeToConvert ) as T;
}
return null;
}
public override void Write( Utf8JsonWriter writer, T value, JsonSerializerOptions options )
{
// Register blob and write $blob reference
var guid = BlobDataSerializer.RegisterBlob( value );
writer.WriteStartObject();
writer.WriteString( "$blob", guid.ToString() );
writer.WriteEndObject();
}
}
}