如何将带有名称的完整对象转换为 json 字符串

How to convert a complete object with its name to a json string

大家好,下面提到的 class 包含嵌套对象:

class Data
    {
        public string Id; 
        pubic Employee employee ;
    }
    class Employee
    {
        pubic Student student;
        public Teacher teacher
    }
    class Student
    {
         age ; 
         id;
    }
    class Teacher
    {
         age ; 
          id;    
    }
I want to fetch the employee data from my object but in JSON format like

 { 
"Employee":{
         "Student":{id:0},
         "Teacher" :{id:0}
    }}

我用了JsonConvert.Serialize(Data.employee);但它将我的 JSON 转换成了这个

{ 
    {
             "Student":{id:0},
             "Teacher" :{id:0}
    } 

}

谁有更好的解决方案?

您需要调整您的对象定义,使其以您想要的方式序列化。尝试将其包装在匿名对象中:

JsonConvert.Serialize(new { Employee = Data.employee});