在C#中从SQL表结果格式化JSON

时间:2013-08-05 21:11:11

标签: c# sql json serialization

我试图以下列方式在c#中格式化JSON。可以说我有下表

col1 col2 col3 col4
comA 1 2 3
comB 4 5 6
comC 7 8 9

我希望我的JSON输出像这样

[{ name: 'comA', data: [1,2,3]
}, { name: 'comB', data: [4,5,6] }, { name: 'comC', data: [7,8,9] }]

我有以下代码

public class ChartLoc
{
    public string Category { get; set; }
    public string Data{ get; set; }
}

public void myFunc(){
    using (SqlConnection con = new SqlConnection(ConnectionString)
    {
        con.Open();
        using (SqlCommand cmd = new SqlCommand("select * from table", con))
        {
            using (SqlDataReader reader = cmd.ExecuteReader())
            {

                List<String> _Category = new List<String>();
                List<String> _Data = new List<String>();

                while (reader.Read())
                {


                    _Data.Add(reader["col2"].ToString() + ',' + reader["col3"].ToString() + ',' + reader["col4"].ToString());

                    if (reader["store"] != DBNull.Value) _Category.Add(reader["col1"].ToString());
                }
                JavaScriptSerializer jss = new JavaScriptSerializer();
                cl.Category = jss.Serialize(_Category); 
                cl.Data = jss.Serialize(_Data);
            }
        }
    }         
}

public class ChartLoc { public string Category { get; set; } public string Data{ get; set; } } public void myFunc(){ using (SqlConnection con = new SqlConnection(ConnectionString) { con.Open(); using (SqlCommand cmd = new SqlCommand("select * from table", con)) { using (SqlDataReader reader = cmd.ExecuteReader()) { List<String> _Category = new List<String>(); List<String> _Data = new List<String>(); while (reader.Read()) { _Data.Add(reader["col2"].ToString() + ',' + reader["col3"].ToString() + ',' + reader["col4"].ToString()); if (reader["store"] != DBNull.Value) _Category.Add(reader["col1"].ToString()); } JavaScriptSerializer jss = new JavaScriptSerializer(); cl.Category = jss.Serialize(_Category); cl.Data = jss.Serialize(_Data); } } } }

虽然这个输出会给我

cl.Category = ['comA','comB','comC'] cl.Data = ['1,2,3','4,5,6','7,8,9']

2 个答案:

答案 0 :(得分:4)

如果您希望输出[{ name: 'comA', data: [1,2,3] }, { name: 'comB', data: [4,5,6] }, { name: 'comC', data: [7,8,9] }],则需要以不同方式序列化您的对象。由于您需要JSON中的数字列表而不是字符串,因此您需要在类定义中将数字表示为List。这样的事情应该有效:

[Serializable]
public class ChartLoc
{
    public string Category { get; set; }
    public List<int> Data{ get; set; }
}

public string myFunc()
{
    string jsonString = "";
    using (SqlConnection con = new SqlConnection(ConnectionString)
    {
        con.Open();
        using (SqlCommand cmd = new SqlCommand("select * from table", con))
        {
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                List<ChartLoc> _ChartLoc = new List<ChartLoc>();

                while (reader.Read())
                {
                    ChartLoc chart = new ChartLoc();
                    chart.Data.Add(int.Parse(reader["col2"].ToString()));
                    chart.Data.Add(int.Parse(reader["col3"].ToString()));
                    chart.Data.Add(int.Parse(reader["col4"].ToString()));

                    if (reader["store"] != DBNull.Value) 
                        chart.Category = reader["col1"].ToString();
                    _ChartLoc.Add(chart);
                }
                JavaScriptSerializer jss = new JavaScriptSerializer();
                jsonString = jss.Serialize(_ChartLoc);
            }
        }
    }
    return jsonString;         
}

答案 1 :(得分:1)

如果您想要包含一组类别/数据配对的单个JSON字符串,则需要序列化单个对象。我会建议一个ChartLoc列表,然后序列化列表。

此外,如果您的Data对象是一个字符串,它将被序列化为一个字符串(即“1,2,3”而不是[1,2,3])。如果你真的想解决这个问题,你需要一组整数。

public class ChartLoc
{
    public string Category { get; set; }
    public List<int> Data { get; set; }
}
...
var chartLocs = new List<ChartLoc>();
chartLocs.Add(new ChartLoc { Category = "comA", Data = new List<int> { 1, 2, 3 } });
chartLocs.Add(new ChartLoc { Category = "comB", Data = new List<int> { 4, 5, 6 } });
chartLocs.Add(new ChartLoc { Category = "comC", Data = new List<int> { 7, 8, 9 } });

JavaScriptSerializer jss = new JavaScriptSerializer();
var json = jss.Serialize(chartLocs);

生成的JSON与您正在寻找的内容更为相似......

  

[{ “类别”: “彗差”, “数据”:[1,2,3]},{ “类别”: “梳状”, “数据”:[4,5,6]},{”类别 “:” COMC”, “数据”:[7,8,9]}]