Home

Tuesday, 19 July 2016

Convert C# Object Value in JSON using C#

Step 1-Write Below Code in Application where Data is fix.If required you can change static data in dynamic.
public class Student
{
    public int Id { get; set; }
public string Name { get; set; }
    public string fatherName { get; set; }
    public DateTime? BirthDate { get; set; }
    public string Phone { get; set; }

    public Student()
    {
        Id = 123; Name = "XYZ";fatherName = "ABC"; BirthDate = new DateTime(1991, 5, 13); Phone = "12345678";
    }
    public Student(int id, string name,String FatherName, DateTime? dob, string phone)
    {
        Id = id; Name = name;fatherName= FatherName; BirthDate = dob; Phone = phone;
    }
}

public class StudentRecord
{
    public IEnumerable<Student> Students { get; set; }

    public StudentRecord()
    {
        Students = new List<Student>
        {
            new Student(1213, "ABC","vbs", new DateTime(1991, 7, 18), "123432123"), 
            new Student(23412, "vtyd","aghgh", new DateTime(1998, 11, 21), "123432123"), 
            new Student(2345, "ghghgh","hjhj", new DateTime(1997, 3, 9), "767678445"), 
        };
    }
}

Step 2-Output Data is in JSon which is Available below.

{
  "Id": 123,
  "Name": "XYZ",
  "fatherName": "ABC",
  "BirthDate": "1991-05-13T00:00:00",
  "Phone": "12345678"
}

{
  "Students": [
    {
      "Id": 1213,
      "Name": "ABC",
      "fatherName": "vbs",
      "BirthDate": "1991-07-18T00:00:00",
      "Phone": "123432123"
    },
    {
      "Id": 23412,
      "Name": "vtyd",
      "fatherName": "aghgh",
      "BirthDate": "1998-11-21T00:00:00",
      "Phone": "123432123"
    },
    {
      "Id": 2345,
      "Name": "ghghgh",
      "fatherName": "hjhj",
      "BirthDate": "1997-03-09T00:00:00",
      "Phone": "767678445"
    }
  ]
}

No comments:

Post a Comment