1

我有 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",
    }
  }
]
4

2 回答 2

2

问题可能是某些类成员是私有的。刚刚测试:

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);

工作正常。

于 2012-10-19T06:05:56.283 回答
1

Department应该包含一个不IEnumerable<Employee>只是一个Employee

于 2012-10-19T06:00:27.937 回答