JsonSerializer.Serialize returns 空对象
JsonSerializer.Serialize returns empty object
我正在尝试将我创建的 class 的对象保存到文件中,但是 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);
}
JsonSerializer.Serialize 仅序列化 public 属性。您只有(私人)字段。
Serialization behavior
By default, all public properties are serialized. You can specify properties to exclude.
...
Currently, fields are excluded.
另请参阅此 feature request
解决方法
您可以使用 Json.NET 并将 [JsonProperty]
添加到私有字段。
Json.NET中的方法是JsonConvert.SerializeObject
我正在尝试将我创建的 class 的对象保存到文件中,但是 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);
}
JsonSerializer.Serialize 仅序列化 public 属性。您只有(私人)字段。
Serialization behavior
By default, all public properties are serialized. You can specify properties to exclude.
...
Currently, fields are excluded.
另请参阅此 feature request
解决方法
您可以使用 Json.NET 并将 [JsonProperty]
添加到私有字段。
Json.NET中的方法是JsonConvert.SerializeObject