C#C
C#3y ago
Sh1be

✅ System.Text.Json serialization problem

hello, I am using System.Text.Json.
I have a struct that has 2 properties: a bool IsDefined and a T value. IsDefined gets set to true when value gets set. This is a container for properties that don't necessarily need to be set, but if they are set, they will get included in the serialization.
The problem is that in the Write method, STJ automatically writes out the property name, which results in this Json if only the name property is set: {"name":"lol","parent_id":"position":}.
The STJ write method:
        if (!value.IsDefined) return;

        switch (value.Value)
        {
            case long:
                if (value.Value != null) writer.WriteStringValue(value.Value.ToString());
                else writer.WriteNullValue();
                break;

            case ulong:
                if (value.Value != null) writer.WriteStringValue(value.Value.ToString());
                else writer.WriteNullValue();
                break;

            default:
                writer.WriteRawValue(JsonSerializer.Serialize(value.Value));
                break;
        }

How can I get around this?
Was this page helpful?