Matt-Crow / GearBox

A C# MMORPG-like game.
0 stars 0 forks source link

Find a better solution for JSON serialization #17

Closed Matt-Crow closed 8 months ago

Matt-Crow commented 1 year ago

Currently, serializing C# objects as JSON requires either generics or type annotations, but these are sub-optimal. Find a better way of doing this.

// given interface IGameObject
Serialize(IGameObject obj) // does not serialize properties of subclass
Serialize<T>(T obj) where T : IGameObject // requires passing generics everywhere

[JsonDerivedType(typeof(Foo), "foo")]
public interface IGameObject // works, but only requires modifying superclass to add subclasses
Matt-Crow commented 1 year ago

Serialization behavior is intentional: https://github.com/dotnet/runtime/issues/31742

Matt-Crow commented 1 year ago

This might help: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/converters-how-to?pivots=dotnet-7-0

Matt-Crow commented 9 months ago

Alternatively, a custom object serialization solution could help remove all the fat associated with JSON keys:

{
    "key1": value1,
    "key2": value2
}

versus

// server
objectStream.Write(value1);
objectStream.Write(value2);

// client
const valueForKey1 = objectStream.read();
const valueForKey2 = objectStream.read();

The client just has to know exactly what to expect on each read.