itzik
itzik

Reputation: 77

JsonSerializer.Serialize returns empty object

I'm trying to save an object of a class I created into a file but the JsonSerializer.Serialize returns {}.

class User : DalObject<User>
{
    private readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    private string email;
    private string nickname;
    private string password;
    private bool LoggedIn;

    public User(string email, string password, string nickname, bool LoggedIn)
    {
        this.email = email;
        this.password = password;
        this.nickname = nickname;
        this.LoggedIn = LoggedIn;
    }

    public string ToJson()
    {
        var options = new JsonSerializerOptions
        {
            WriteIndented = true
        };
        log.Debug("User " + this.email + " saved");
        return JsonSerializer.Serialize(this, options);
    }

Upvotes: 4

Views: 5703

Answers (1)

Julian
Julian

Reputation: 36770

The JsonSerializer.Serialize only serializes public properties. You have only (private) fields.

Serialization behavior

  • By default, all public properties are serialized. You can specify properties to exclude.

  • ...

  • Currently, fields are excluded.

From Microsoft docs

Possible since .NET 5

Since .NET 5 its possible to include fields. Use the JsonSerializerOptions.IncludeFields global setting or the [JsonInclude] attribute to include fields when serializing or deserializing.

See https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0#include-fields

Work around before .NET 5

You could use Json.NET and add the [JsonProperty] to the private fields.

The method in Json.NET is JsonConvert.SerializeObject

Upvotes: 10

Related Questions