gpt4 book ai didi

c# - JsonSerializer.Serialize 返回空对象

转载 作者:行者123 更新时间:2023-12-01 21:41:32 31 4
gpt4 key购买 nike

我正在尝试将我创建的类的对象保存到文件中,但 JsonSerializer.Serialize 返回 {}

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)属性。您只有(私有(private))字段。

Serialization behavior

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

  • ...

  • Currently, fields are excluded.

来自 Microsoft docs

可能自 .NET 5 以来

从 .NET 5 开始,可以包含字段。使用 JsonSerializerOptions.IncludeFields 全局设置或 [JsonInclude] 属性在序列化或反序列化时包含字段。

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

解决 .NET 5 之前的问题

你可以使用 Json.NET并将 [JsonProperty] 添加到私有(private)字段。

Json.NET中的方法是JsonConvert.SerializeObject

关于c# - JsonSerializer.Serialize 返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61292695/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com