Start Debugging
2023-09-05 Aktualisiert 2023-11-05 csharpdotnetdotnet-8 Edit on GitHub

.NET 8 nicht-öffentliche Member in die JSON-Serialisierung einbeziehen

Erfahren Sie, wie Sie in .NET 8 mit dem Attribut JsonInclude private, protected und internal Properties in die JSON-Serialisierung aufnehmen.

Ab .NET 8 lassen sich beim Einsatz von System.Text.Json auch nicht-öffentliche Properties in die Serialisierung einbeziehen. Dazu versehen Sie die nicht-öffentliche Property einfach mit dem Attribut JsonIncludeAttribute.

[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)]
public sealed class JsonIncludeAttribute : System.Text.Json.Serialization.JsonAttribute

Das Attribut funktioniert mit jedem nicht-öffentlichen Modifier, also private, protected oder internal. Sehen wir uns ein Beispiel an:

string json = JsonSerializer.Serialize(new MyClass(1, 2, 3));

Console.WriteLine(json);

public class MyClass
{
    public MyClass(int privateProperty, int protectedProperty, int internalProperty)
    {
        PrivateProperty = privateProperty;
        ProtectedProperty = protectedProperty;
        InternalProperty = internalProperty;
    }

    [JsonInclude]
    private int PrivateProperty { get; }

    [JsonInclude]
    protected int ProtectedProperty { get; }

    [JsonInclude]
    internal int InternalProperty { get; }
}

Wie zu erwarten, ergibt das die folgende Ausgabe:

{"PrivateProperty":1,"ProtectedProperty":2,"InternalProperty":3}

Comments

Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.

< Zurück