How to convert C# model classes to JSON objects?

How to convert C# model classes to JSON objects?

In this post, how to convert C# model classes to JSON objects?

Commonly used namespaces System.Collections.Generic, System.Linq is automatically included; however, for less commonly used .NET Framework types you may add those namespaces. Example: To use the type IP include "using System.Net;".

 public class Contact
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public DateTime? DOB { get; set; }
            public string Phone { get; set; }
            public Address Address { get; set; }

            public Contact()
            {
                this.Id = 8113; this.Name = "Usingcsharp"; this.DOB = new DateTime(1980, 5, 13); this.Phone = "788-755-7212";
                this.Address = new Address();
            }
        }

        // This will be serialized into a JSON array of Contact objects
        public class ContactsCollection
        {
            public ICollection<Contact> Contacts { get; set; }

            public ContactsCollection()
            {
                // initialize array of objects in default constructor to generate sample data
                this.Contacts = new List<Contact>
        {
            new Contact { Id = 8113, Name = "Usingcsharp", DOB = new DateTime(1980, 5, 13), Phone = "788-755-7212", 
                          Address = new Address { Street = "7627 Sunset", City = "San Diego", State = "CA", PostalCode = "72115" } }, 
            new Contact { Id = 8114, Name = "Mary Lamb", DOB =  new DateTime(1974, 10, 21), Phone = "737-755-7212",
                          Address = new Address { Street = "7111 Industrial Area", City = "Dallas", State = "TX", PostalCode = "79245" } }, 
            new Contact { Id = 8115, Name = "Shankar", DOB = new DateTime(1968, 2, 8), Phone ="743-755-7212",
                          Address = null }
        };
            }
        }

 

2021-10-03