Reputation: 77
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
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
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.
You could use Json.NET and add the [JsonProperty]
to the private fields.
The method in Json.NET is JsonConvert.SerializeObject
Upvotes: 10