C#:List<CustomClass>的JSON序列化返回空数组?

问题描述 投票:0回答:3

所以,我有一个像这样的自定义类“用户”:

class User
    {
        string firstname;
        string lastname;
        string proposedname;
        public User(string firstname, string lastname)
        {
            this.firstname = firstname;
            this.lastname = lastname;
            this.proposedname = $"{firstname}.{lastname}".ToLower();
        }
}

另一个类“UserCreator”有一个方法“GenerateList”和一个方法“WriteList”以及一个简单的列表字段:

public class UserCreator
    {
        internal List<User> Users;
        public UserCreator(int n = 1000)
        {
            Users = new List<User>();
            this.GenerateList(n);
        }
       public  void WriteList(string outputPath)
        {
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(this.Users, Newtonsoft.Json.Formatting.Indented);
            System.IO.File.WriteAllText(outputPath, json);

        }

        void GenerateList(int amount)
        {
            List<User> result = new List<User>();
            ///...
            this.Users = result;
        }
    }

一切工作正常,直到到达 WriteList() 中的序列化部分。我没有按预期工作,而是得到这样的结果:

[
  {},
  {},
  {},
  {},
  {},
  {},
  {},
  {}
]

我猜这与我使用自定义类的列表有关。这是 Newtonsoft.Json 的已知限制吗?或者可能是由于访问修饰符?

c# json.net
3个回答
6
投票

您声明类的方式完全封装了您的所有用户数据。

这些不是属性,而是实例字段(或者类成员,如果我们挑剔的话),并且默认情况下它们是私有的。相反,请注意您的访问修饰符 至少为每个属性公开一个公共 getter,如下所示:

public class User
{
    public string firstname { get; private set;}
    public string lastname { get; private set;}
    public string proposedname { get ; private set; }
    public User(string firstname, string lastname)
    {
        this.firstname = firstname;
        this.lastname = lastname;
        this.proposedname = $"{firstname}.{lastname}".ToLower();
    }
}

1
投票

默认访问级别是私有的,因此您的名字、姓氏、提议名称都是私有字段。您可以将其更改为公开。或者您也可以为 jsonserialzation 设置编写自定义合约解析器。


0
投票

我知道 OP 使用 Newtonsoft.JSON,但我在使用 .NET 7 的 System.Text.Json 序列化程序时遇到了同样的问题,并且将我的所有属性标记为公共。对我来说,解决方法是将

[JsonInclude]
属性添加到我的 List 属性中。

所以这不起作用:

public class People
{
    public List<User> Users = new();
}

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set;}
}
...
var people = new People();

// populate people with users here...

var json = System.Text.Json.JsonSerializer.Serialize(people);

json
字符串始终只是
{}

[JsonInclude]
属性添加到列表中,如下所示修复了该问题:

public class People
{
    [JsonInclude]
    public List<User> Users = new();
}

希望这可以帮助其他偶然发现这个问题但正在使用 System.Text.Json 序列化器的人。

© www.soinside.com 2019 - 2024. All rights reserved.