在C#中使用JSON.NET创建JSON多层次



我有2个类:

class Employee
{
    string name;
    string age;
}
class Departments
{
    string branch;
    Employee A;
}

声明新列表:

List<Departments> lstDp = new List<Departments>();

获得/设置后,并将员工添加到列表中...我有一个部门列表包括员工信息。然后:

string json = JsonConvert.SerializeObject(lstDp, Newtonsoft.Json.Formatting.Indented);

但是输出JSON字符串仅包含元素"分支"。这怎么了?我想要这样的输出:

[
  {
    "branch": "NY",
    "Employee": {
        "name": "John Smith",
        "age": "29",
    }
  }
]

问题可能是某些班级成员是私人的。刚刚测试:

class Employee
{
    public string Name { get; set; }
    public string Age { get; set; }
}
class Departments
{
    public string Branch { get; set; }
    public Employee Employee { get; set; }
}

var lstDp = new List<Departments> {
            new Departments {
                Branch = "NY",
                Employee = new Employee { Age = "29", Name = "John Smith" }
            }
        };
var json = JsonConvert.SerializeObject(lstDp, Formatting.Indented);

工作正常。

Department不仅包含 IEnumerable<Employee> Employee

相关内容

  • 没有找到相关文章

最新更新