[英]Create JSON multi-level with Json.NET in c#
i have 2 class: 我有2个课程:
class Employee
{
string name;
string age;
}
class Departments
{
string branch;
Employee A;
}
Declare new list: 声明新列表:
List<Departments> lstDp = new List<Departments>();
after get/set and Add Employee into the list ... i have a LIST of Departments include Employee info. 获取/设置并将员工添加到列表中...我有一个部门列表包括员工信息。 And then:
接着:
string json = JsonConvert.SerializeObject(lstDp, Newtonsoft.Json.Formatting.Indented);
but the output JSON string only contain element "branch". 但输出JSON字符串只包含元素“branch”。 What's wrong with this?
这有什么问题? I want the output like this:
我希望输出像这样:
[
{
"branch": "NY",
"Employee": {
"name": "John Smith",
"age": "29",
}
}
]
The problem can be that some of class members is private. 问题可能是一些班级成员是私人的。 Just tested:
刚测过:
class Employee
{
public string Name { get; set; }
public string Age { get; set; }
}
class Departments
{
public string Branch { get; set; }
public Employee Employee { get; set; }
}
And 和
var lstDp = new List<Departments> {
new Departments {
Branch = "NY",
Employee = new Employee { Age = "29", Name = "John Smith" }
}
};
var json = JsonConvert.SerializeObject(lstDp, Formatting.Indented);
Works fine. 工作正常。
Department
应该包含一个IEnumerable<Employee>
而不仅仅是一个Employee
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.