Search code examples
c#jsonnsjsonserialization

JSON Class with a List of another Class


I'll try to explain this as best as I can. I have a class called Prospect which contains strings of email, company, firstname, lastname, phone.

I have the requirement to ouput Prospect information in JSON in the format of

[
   {"email":"[email protected]",
      "properties":[
      {
        "property":"company",
        "value": "Company Name"
      },
        "property":"firstname",
        "value":"John"
      },
        "property":"surname",
         "value":"Smith"
      },
        "property":"phone",
        "value":"01234567891"
      }]
  }
]

I need to output JSON of all prospects I capture. I have tried this by creating a class of Customer:

public class Customer
{
    public string email { get; set; }
    public List<Property> properties { get; set; }

}

and a class of Property:

public class Property
{
    public string property { get; set; }
    public string value { get; set; }
}

I cant for the life of me get the result i am after. I thinks its the List of Property in the Customer class. If i change the List to a string and define only one value here, the output is fine.

Please help :(


Solution

  • [SOLVED]

    Thank you to everyone who provided comments. Your guidance helped me resolve my issue.

            public class Customer
        {
            public string email { get; set; }
            public List<Property> properties { get; set; }
        }
    
        public class Property
        {
            public string property { get; set; }
            public string value { get; set; }
        }
    
    
    
        private void button1_Click(object sender, EventArgs e)
        {
    
    
            Customer _c = new Customer();
            _c.email = email.Text;
            _c.properties = new List<Property>();
            _c.properties.Add(new Property{ property = "company", value = company.Text });
            _c.properties.Add(new Property { property = "website", value = website.Text });
            _c.properties.Add(new Property { property = "firstname", value = firstname.Text });
            _c.properties.Add(new Property { property = "lastname", value = lastname.Text });
            _c.properties.Add(new Property { property = "phone", value = phone.Text });
    
            string json = JsonConvert.SerializeObject(_c, Formatting.Indented);
            outputBox.Text = json;
    
        }