© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
221 replies
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":}
{"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;
        }
        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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

❔ ✅ System.Text.Json paths
C#CC# / help
3y ago
❔ C# Dictionary Json Serialization problems
C#CC# / help
4y ago
System.Text.Json Source Generators
C#CC# / help
3y ago
Create JSON objects from System.Text.Json
C#CC# / help
2y ago