Converting a dataset to JSON using .NET 3.5 in C#

前端 未结 5 1643

I have been searching for a simple way to convert a dataset from a PostgreSQL database to JSON for use in a project that I am building.

This is my first time using J

相关标签:
5条回答
  • 2020-12-19 09:07

    For others looking at this topic:

    Here is the simplest way to convert a dataset to a JSON array as json_encode (PHP) does with ASP.Net:

    using Newtonsoft.Json;
    
    public static string ds2json(DataSet ds) {
        return JsonConvert.SerializeObject(ds, Formatting.Indented);
    }
    
    0 讨论(0)
  • 2020-12-19 09:10
    public static string GetJSONString(DataTable Dt)
    {
        string[] StrDc = new string[Dt.Columns.Count];
        string HeadStr = string.Empty;
    
        for (int i = 0; i < Dt.Columns.Count; i++)
        {
            StrDc[i] = Dt.Columns[i].Caption;
            HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
        }
    
        HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
    
        StringBuilder Sb = new StringBuilder();
        Sb.Append("{\"" + Dt.TableName + "\" : [");
    
        for (int i = 0; i < Dt.Rows.Count; i++)
        {
            string TempStr = HeadStr;
            Sb.Append("{");
    
            for (int j = 0; j < Dt.Columns.Count; j++)
            {
                TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString());
            }
            Sb.Append(TempStr + "},");
        }
    
        Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
        Sb.Append("]}");
    
        return Sb.ToString();
    }
    

    var JObject = eval('(' + JSONString + ');');
    for(var i = 0; i < JObject .Employees.length; i++)
    {
    
    var val1 = JObject.Employees[i].EmployeeID;
    
    var val2 = JObject.Employees[i].NationalIDNumber;
    
    var val3 = JObject.Employees[i].Title;
    
    var val4 = JObject.Employees[i].BirthDate;
    
    var val5 = JObject .Employees[i].HireDate ;
    
    }
    
    0 讨论(0)
  • 2020-12-19 09:20
    public static T WriteJson<T>(this System.Data.DataSet dataSet)
    {
        try
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(dataSet.GetXml());
            return (T)Convert.ChangeType(JsonConvert.SerializeXmlNode(doc).Replace("null", "\"\"").Replace("'", "\'"), typeof(T));
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    
    0 讨论(0)
  • 2020-12-19 09:25

    Use Newtonsofts Json.Net and check out DataTable JSON Serialization in JSON.NET and JavaScriptSerializer where it's used to create a DataSet-to-JSON converter.

    0 讨论(0)
  • 2020-12-19 09:25

    Maybe you've heard about the system.runtime.serialization.json namespace in the newly announced .NET Framework 4.0.

    0 讨论(0)
提交回复
热议问题