1

i have 2 class:

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". What's wrong with this? I want the output like this:

[
  {
    "branch": "NY",
    "Employee": {
        "name": "John Smith",
        "age": "29",
    }
  }
]
1
  • 1) your fields are not public, they won't be serialized 2) Your json is not correct. There will be no Employee string in the output. It will be A 3) A is not a list. It is a single employee. Commented Oct 19, 2012 at 6:07

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

The Departmentshould contain an IEnumerable<Employee> not just an Employee

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.