Niteesh Kumar
Niteesh Kumar

Reputation: 213

convert mvc c# model class to json from datatable

I have a C# class and data table.

DataTable:

+---------+-----------------+---------------+---------+---------+--------------+
| Pers_Id | Pers_First_Name | Pers_Last_Name| OrderNu | OrderId |  Pers_Update |
+---------+-----------------+---------------+---------+---------+--------------+
| 1       |       ABC       |        Ln     |   76454 |  1      |   2018-03-25 |
+---------+-----------------+---------------+---------+---------+--------------+
| 1       |       ABC       |        Ln     |   76578 |  2      |   2018-03-25 |
+---------+-----------------+---------------+---------+---------+--------------+

Class:

public class Person
{
    public int Pers_Id { get; set; }
    public string Pers_First_Name { get; set; }
    public string Pers_Last_Name { get; set; }
    public DateTime Pers_Update { get; set; }
    public List<Order> Order_List { get; set; }

    public class Order
    {
        public int OrderID { get; set; }
        public string OrderNu { get; set; }
    }
}

I need to bind this class from data table and need to convert it into json object for rest API response in asp .net web API.

When i am binding i am getting json duplicate but result should be like this

{ "Pers_Id": 1, "Pers_First_Name": "ABC", "Pers_Last_Name": "LN", "Pers_Update": "", "Order_List": [ { "OrderID": "1", "OrderNu": "76454" }, { "OrderID": "2", "OrderNu": "76578" } ] }

Upvotes: 0

Views: 2051

Answers (2)

Fatih Sağlam
Fatih Sağlam

Reputation: 46

First;

using System.Web.Script.Serialization;

Second; If your data table's class isn't same with your Person class, then you should create a new class of datatable version for your persons.

    public class Person
    {
        public int Pers_Id { get; set; }
        public string Pers_First_Name { get; set; }
        public string Pers_Last_Name { get; set; }
        public DateTime Pers_Update { get; set; }
        public List<Order> Order_List { get; set; }
        public class Order
        {
            public int OrderID { get; set; }
            public int OrderNu { get; set; }
        }
    }


    //You need a class that fits to your DataTable
    public class PersonDataTable
    {
        public int Pers_Id { get; set; }
        public string Pers_First_Name { get; set; }
        public string Pers_Last_Name { get; set; }
        public DateTime Pers_Update { get; set; }
        public int OrderId { get; set; }
        public int OrderNu { get; set; }
    }

In your method;

    public string ReturnGoodPeopleJsonFormat()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();//Needed for converting an object to Json string.
        List<PersonDataTable> personDataTableList = new List<PersonDataTable>();//Needed for filling your data from in program or from database
        List<Person> personList = new List<Person>();//Needed 'to be converted' in to Json string


        //Add items to your DataTable list manually
        personDataTableList.Add(
            new PersonDataTable { Pers_Id = 1, Pers_First_Name = "ABC", Pers_Last_Name = "Ln", Pers_Update = Convert.ToDateTime("2018-03-25"), OrderId = 1, OrderNu = 76454 });
        personDataTableList.Add(
            new PersonDataTable { Pers_Id = 1, Pers_First_Name = "ABC", Pers_Last_Name = "Ln", Pers_Update = Convert.ToDateTime("2018-03-25"), OrderId = 2, OrderNu = 76578 });

        //or from database
        // personDataTableList.AddRange(myDatabaseModel.DataTables.ToList());



        //Now group your data by Pers_Id //We are grouping this because we don't want same person 2 or 3 time, we want one person just one time but get all orders in it. That's why we need to group them by Pers_Id
        foreach (var personGroup in personDataTableList.GroupBy(x => x.Pers_Id))
        {
            List<Person.Order> orderList = new List<Person.Order>();

            foreach (var dataTablePerson in personDataTableList.Where(x => x.Pers_Id == personGroup.Key))
            {
                //Get all orders of personGroup one by one in to an Order list from PersonDataTable list by using Pers_Id like a foreign key.
                ///This personGroup.Key is nothing but Pers_Id\\\ 
                orderList.Add(new Person.Order { OrderID = dataTablePerson.OrderId, OrderNu = dataTablePerson.OrderNu });
            }

            //Add new Person object to your personList if you don't have it before (by checking Pers_Id)
            if (personList.Where(x => x.Pers_Id == personGroup.Key).Count() == 0) //This personGroup.Key is nothing but Pers_Id
            {
                personList.Add(new Person
                {
                    Pers_Id = personDataTableList.Where(x => x.Pers_Id == personGroup.Key).FirstOrDefault().Pers_Id,
                    Pers_First_Name = personDataTableList.Where(x => x.Pers_Id == personGroup.Key).FirstOrDefault().Pers_First_Name,
                    Pers_Last_Name = personDataTableList.Where(x => x.Pers_Id == personGroup.Key).FirstOrDefault().Pers_Last_Name,
                    Pers_Update = personDataTableList.Where(x => x.Pers_Id == personGroup.Key).FirstOrDefault().Pers_Update,
                    Order_List = orderList
                });
            }

        }
        string JsonString = js.Serialize(personList);
        return JsonString;
    }

The result is like this:

[{"Pers_Id":1,"Pers_First_Name":"ABC","Pers_Last_Name":"Ln","Pers_Update":"/Date(1521925200000)/","Order_List":[{"OrderID":1,"OrderNu":76454},{"OrderID":2,"OrderNu":76578}]}]

Upvotes: 0

d.jazel
d.jazel

Reputation: 87

When you have an object (f.eks. your Employee object in this example), you should be able to return it like this:

return Content(JsonConvert.SerializeObject(employee), "application/json");

More info here: https://stackoverflow.com/a/34091196/4034346

Upvotes: 1

Related Questions