使用格式C#创建JSON文件

时间:2016-11-04 09:05:52

标签: c# json.net

我需要以下列格式创建JSON文件:

"Result": [
         [ "Date", "Name", "Address", "Age" ],
         [ "MMDDYYYY", "Name1", "Add1", "15" ],
         [ "MMDDYYYY", "Name2", "Add2", "20" ]

结果的数据为List<JArray>,由List<string>填充,由DataTable填写如下:

var jArrayList = new List<JArray>();
var rowData = new List<string>();
for (int i = 0; i < table.Rows.Count; i++)
{
   var rowData = new List<string>(table.Columns.Count);
   DataRow dataRow = table.Rows[i];

   foreach (DataColumn dataColumn in table.Columns)
   {
      if (i > 0)
      {
         rowData.Add(dataRow[dataColumn].ToString());
      }
    }

    if (rowData.Any())
    {
       jArrayList.Add(new JArray(rowData));
    }
 }

 if (jArrayList.Any())
 {
    var jobj = new JObject( new JProperty("Result",
                            from p in jArrayList
                            select p));
     jObjList.Add(jobj);
  }

  var outputJson = new JObject(new JProperty("Entries",
                                        from p in jObjList
                                        select p));
  var outputString = outputJson.ToString();

当我执行此代码时,它会在新行中编写所有内容:

"Result": [
    [
      "Date",
      "Name",
      "Address",
      "Age"
    ],
    [
      "MMDDYYYY",
      "Name1",
      "Add1",
      "15"
    ],
    [
      "MMDDYYYY",
      "Name2",
      "Add2",
      "20"
    ],

如何格式化以这种方式编写?

"Result": [
     [ "Date", "Name", "Address", "Age" ],
     [ "MMDDYYYY", "Name1", "Add1", "15" ],
     [ "MMDDYYYY", "Name2", "Add2", "20" ]

1 个答案:

答案 0 :(得分:1)

下面:

string json = "\"Result\": [\r\n    [\r\n      \"Date\",\r\n      \"Name\",\r\n      \"Address\",\r\n      \"Age\"\r\n    ],\r\n    [\r\n      \"MMDDYYYY\",\r\n      \"Name1\",\r\n      \"Add1\",\r\n      \"15\"\r\n    ],\r\n    [\r\n      \"MMDDYYYY\",\r\n      \"Name2\",\r\n      \"Add2\",\r\n      \"20\"\r\n    ],";
            var withoutEnter = json.Replace(Environment.NewLine, "");
            var splited = withoutEnter.Split('[');
            var formattedJson = splited[0];
            for (int i = 1; i < splited.Length; i++)
            {
                formattedJson = formattedJson + "[" + splited[i] + "\n";
            }

我已经将你的json样本复制粘贴并解析它以删除所有输入,然后为每个组添加回输入。对不起凌乱的代码:)