1

I have such structure

public class Agent
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
public class Student
{
    public int Id { get; set; }
    public List<Agent> Agents { get; set; }
}
public class RootObject
{
    public List<Student> Students { get; set; }

and this code

RootObject obj = JsonConvert.DeserializeObject<RootObject>(Out);
foreach (Student stu in obj.Students)
{   
    ...
    foreach (Agent Agent in stu.Agents)
    {
        ...
    }
}

foreach (Agent Agent in stu.Agents)

get error

Object reference not set to an instance of an object.

Tell me how I should correctly declare objects

1 Answers1

0

You can add Agents list initialization in Student class default constructor. It will help you to handle absence of Agents in your JSON.

Try this.

public class Student
{
    public int Id { get; set; }
    public List<Agent> Agents { get; set; }

    public Student()
    {
        Agents = new List<Agent>();
    }
}
aleha
  • 7,140
  • 2
  • 34
  • 41