尝试使用匿名类型生成自定义JSON

问题描述 投票:0回答:1

我最近一直在学习如何从数据表生成jsongeojson流。至少可以说这是一场艰苦的战斗。

当前,我正在尝试为图表创建自定义JSON流。这是正确的JSON格式:

{
    "labels": ["January","February","March","April"],
    "datasets": 
    [{
        "label": "NAME",
        "data": [1,2,3,4]
    },{
        "label": "NUM",
        "data": [11,12,13,14]
    }]
}

我的数据表看起来像这样:

monthname   Data1   Data2
January     1       11
February    2       12
March       3       13
April       4       14  

到目前为止,这就是我所拥有的:

public static string DataTableToCustomJSONString(DataTable dataTable)
{

    string monthName = string.Empty;
    string data1 = string.Empty;
    string data2 = string.Empty;
    foreach (DataRow row in dataTable.Rows)
    {
        monthName += row["MonthName"].ToString() + ",";
        data1 += row["data1"].ToString() + ",";
        data2 += row["data2"].ToString() + ",";
    }
    monthName = monthName.Remove(monthName.Length - 1);
    data1 = data1.Remove(data1.Length - 1);
    data2 = data2.Remove(data2.Length - 1);

    var obj = new
    {
        labels = monthName,
        datasets = new dynamic [] {
        new { label = "NAME", Data = data1 }
        ,
        new { label = "NUM", Data = data2 },
    }
    };
    return JsonConvert.SerializeObject(obj, Formatting.Indented);

}

哪个返回以下json:

{
  "labels": "January,February,March,April",
  "datasets": [
    {
      "label": "NAME",
      "data": "1,2,3,4"
    },
    {
      "label": "NUM",
      "data": "11,12,13,14"
    }
  ]
}

如您所见,月份应该用方括号括起来,并且每个月都有双引号(["January","February","March","April"]而不是"January,February,March,April")。

此外,data属性应类似于此[2,3,4,5],但由双引号包围(`“ 11,12,13,14”'')。

此外,我不确定在数据表中进行迭代是否是生成months字符串的最佳方法。

感谢您的任何帮助。

c# json wcf visual-studio-2013
1个回答
1
投票

执行此操作时:

monthName += row["MonthName"].ToString() + ",";

您正在告诉它将值连接成一个长字符串,中间用逗号隔开。这正是它为您所做的。

如果要使其成为数组,则可以使用List<string>并添加每个值。它们将被序列化为JSON数组:

var months = new List<string>();
var data1 = new List<string>();
var data2 = new List<string>();
foreach (DataRow row in dataTable.Rows)
{
    months.Add(row["MonthName"].ToString());
    data1.Add(row["data1"].ToString());
    data2.Add(row["data2"].ToString());
}

然后,您也不需要那些删除最后一个逗号的行。

© www.soinside.com 2019 - 2024. All rights reserved.