【问题标题】:Dataset to JSON using C#/VB.Net使用 C#/VB.Net 将数据集转换为 JSON
【发布时间】:2016-02-26 20:05:22
【问题描述】:

我有一个包含以下数据的数据集:

我想将此数据转换为以下格式的 JSON:

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

我可以在 VB.Net 中使用更快的方法将其直接转换为 JSON 吗?我应该创建类并列出并迭代数据集以创建嵌套类的对象然后序列化它还是可以以不同的方式实现?有人可以告诉我将数据集序列化为 JSON 的方法吗?我对 C# 也很好。

【问题讨论】:

  • 首先根据您的要求将此数据集转换为实体列表,然后将其序列化。
  • 我的问题不是“如何将数据集序列化为 JSON”。我的问题指定“使用 VB.Net 到 JSON 的数据集”。这意味着我需要编写一个代码,该代码从数据集中获取行并为其属性分配三个不同的类,然后对其进行序列化。我无法迭代嵌套对象。
  • 使用LINQ或者foreach遍历所有的行列,准备一个需要序列化的实体列表。

标签: c# json vb.net dataset


【解决方案1】:

你需要有如下的嵌套类:

[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; }
}

在类中填充数据后,您可以使用 JavaScriptSerializer 类,它已经是 System.Web.Script.Serialization 的一部分,如下所示:

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

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

//您可以使用以下代码填充资源类:

// 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);

【讨论】:

  • 谢谢。我已经定义了类结构。对我来说真正的挑战是迭代数据集并从中分配类的属性,然后序列化对象。我只是无法让迭代工作。
  • 编辑代码以从数据集中添加资源类的填充。
【解决方案2】:

如上所述,你可以使用newtonsoft。但是没有这个默认行为。要创建一个更通用的解决方案,您可以为纽特诺夫编写自定义JSONConverter。并为您的项目进行序列化或反序列化的清洁方式。

参见:http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization/或@ 487654322 @。

【讨论】:

    【解决方案3】:

    如前所述,newtonsoft 是一个真正的美女。你可以这样做:

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

    【讨论】:

    • 我的问题不在于如何序列化。我知道 newtonsoft 可以为我序列化对象。我的问题是将线性数据转换为嵌套对象。对不起,如果我没有在我的问题中很好地解释它。
    【解决方案4】:

    用于 .NET JSON Newtonsofts JSON http://www.newtonsoft.com/json。它可以满足您的一切需求!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      相关资源
      最近更新 更多