简体   繁体   中英

Dataset to JSON using C#/VB.Net

I have a dataset with the following data: 在此输入图像描述

I want to convert this data into JSON in the following format:

{
    "Resource": [
        {
            "resourceID": "1",
            "resourceName": "Jonathan",
            "Customer": [
                {
                    "customerID": "1",
                    "firstName": "Alec",
                    "lastName": "Stewart",
                    "Appointments": [
                        {
                            "appointmentID": "1",
                            "startDate": "01-01-2015",
                            "endDate": "01-01-2015"
                        },
                        {
                            "appointmentID": "2",
                            "startDate": "01-01-2015",
                            "endDate":"01-01-2015",
                        }
                    ]
                },
                {
                    "customerID": "2",
                    "firstName": "Chris",
                    "lastName": "Douglas",
                    "Appointments": [
                        {
                            "appointmentID": "3",
                            "startDate": "01-01-2015",
                            "endDate": "01-01-2015",
                        }
                    ]
                }
            ]
        },
        {
            "resourceID": "2",
            "resourceName": "Matthew",
            "Customer": [
                {
                    "customerID": "3",
                    "firstName": "Shirley",
                    "lastName": "Graham",
                    "Appointments": [
                        {
                            "appointmentID": "4",
                            "startDate": "01-01-2015",
                            "endDate": "01-01-2015",
                        },
                        {
                            "appointmentID": "5",
                            "startDate": "01-01-2015",
                            "endDate": "01-01-2015"
                        }
                    ]
                },
                {
                    "customerID": "4",
                    "firstName": "Ricardo",
                    "lastName": "Powell",
                    "Appointments": [
                        {
                            "appointmentID": "6",
                            "startDate": "01-01-2015",
                            "endDate": "01-01-2015"
                        }
                    ]
                }
            ]
        }
    ]
}

Is there any faster way that I can use in VB.Net to convert it directly to JSON? Should I go with creating classes and list and iterate the dataset to create object of nested classes and then serialize it or it can be achieved in a different way? Can someone tell me about the way to serialize the dataset to JSON? I am okay with C# as well.

You need to have nested class like below:

[Serializable]
public class Resource
{
    public string resourceID { get; set; }
    public string resourceName { get; set; }
    public List<Customer> Customers { get; set; }
}

public class Customer
{
    public string customerID { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public List<Appointment> Appointments { get; set; }
}

public class Appointment
{
    public string appointmentID { get; set; }
    public string startDate { get; set; }
    public string endDate { get; set; }
}

After you populate the data in your class, you can use JavaScriptSerializer class which is already part of System.Web.Script.Serialization like below:

var resources = new List<Resource>();
//populate resources data here

JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
var resourceJSON = serializer.Serialize(resources); //result

//You can populate resources class using code below:

// Fill the DataSet
DataSet dataSet = new DataSet("tblResources");
adapter.Fill(dataSet);

//Populate nested class base on DataSet
var resources = new List<Resource>();

string currentResourceID = string.Empty;
string currentCustomerID = string.Empty;
int totalRows = dataSet.Tables[0].Rows.Count;

var resource = new Resource();
var customer = new Customer();
var customers = new List<Customer>();
var appointments = new List<Appointment>();
bool newResource = false;
bool newCustomer = false;

for (int i = 0; i < totalRows; i++)
{
    var resourceID = dataSet.Tables[0].Rows[i]["resourceID"].ToString();
    var resourceName = dataSet.Tables[0].Rows[i]["resourceName"].ToString();
    var customerID = dataSet.Tables[0].Rows[i]["customerID"].ToString();
    var firstName = dataSet.Tables[0].Rows[i]["firstName"].ToString();
    var lastName = dataSet.Tables[0].Rows[i]["lastName"].ToString();
    var appointmentID = dataSet.Tables[0].Rows[i]["appointmentID"].ToString();
    var startDate = dataSet.Tables[0].Rows[i]["startDate"].ToString();
    var endDate = dataSet.Tables[0].Rows[i]["endDate"].ToString();

    if (!currentResourceID.Equals(resourceID))
    {
        currentResourceID = resourceID;

        resource = new Resource()
        {
            resourceID = resourceID,
            resourceName = resourceName
        };

        resources.Add(resource);

        newResource = true;
    }
    else
    {
        newResource = false;
    }

    if (newResource)
    {
        customers = new List<Customer>();

        resource.Customers = customers;
        currentCustomerID = string.Empty;

    }

    if (!currentCustomerID.Equals(customerID))
    {
        currentCustomerID = customerID;

        customer = new Customer()
        {
            customerID = customerID,
            firstName = firstName,
            lastName = lastName
        };


        customers.Add(customer);

        newCustomer = true;
    }
    else
    {
        newCustomer = false;
    }

    if (newCustomer)
    {
        appointments = new List<Appointment>();

        customer.Appointments = appointments;

    }

    var appointment = new Appointment()
    {
        appointmentID = appointmentID,
        startDate = startDate,
        endDate = endDate
    };

    appointments.Add(appointment);

}

//Convert nested class to json
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
var resourceJSON = serializer.Serialize(resources);

As already mentioned, newtonsoft is a real beauty. You could do this:

string json = JsonConvert.SerializeObject(yourdataset, Formatting.Indented);

Use for .NET <> JSON Newtonsofts JSON at http://www.newtonsoft.com/json . It does everything and more what you need!

As mentioned u can use NewtonSoft for this. But there is no default behavior for this. To create a more generic solution u can write a Custom JsonConverter for the Newtonsoft. And implement a clean way for your project to serialize or deserialize.

See a example at: http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization/ or http://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM