我有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”。这有什么问题?我希望输出像这样:
[
{
"branch": "NY",
"Employee": {
"name": "John Smith",
"age": "29",
}
}
]
答案 0 :(得分: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);
工作正常。
答案 1 :(得分:1)
Department
应包含IEnumerable<Employee>
,而不仅仅是Employee