0

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" } ] }

3
  • 1
    Just return the class object via the web api controller. By default the web api will convert the response to json Commented Mar 11, 2018 at 18:48
  • You can fill List<Person> from DataTable and use json.net to serialize the list. Commented Mar 11, 2018 at 18:50
  • @Marcus, but how to bind this , actually getting order_list null or duplicate Commented Mar 11, 2018 at 18:51

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for answer but I know this actually I want to know how to bind this class with table and in json object I want distinct person with all his orders
hi @NiteeshKumar I assume your table is located in your application (and not in JSon object) cause you are trying to create a json object and send it from the data that is stored on your system, right?
In that case all you need to do is simply get the instance of your Person object. You can do that either via Direct database call (how to MSSQL DB call: stackoverflow.com/a/14172067/4034346), or via Entity Framework
I have a buisness layer and getting a data table from that and by looping I am setting the model value but getting duplicate records in json ..so I want to know the proper way of coding that how to set model by data table through looping and send back that model to response
0

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}]}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.