简体   繁体   English

从 C# 的动态列表创建 JSON 对象

[英]Create JSON object from dynamic list from C#

I have a list of two dimensions dynamic as follows :我有一个二维动态列表,如下所示:

List<dynamic> tableContent = new List<dynamic>();

List<dynamic> rowHeader = new List<dynamic>();
rowHeader.add("First header");
rowHeader.add("Second header");
rowHeader.add("Third header");
tableContent.add(rowHeader);

for (int i = 0; i < 5; i++) {
  List<dynamic> rowContent = new List<dynamic>();
  rowContent.add("1");
  rowContent.add("2");
  rowContent.add("3");
  tableContent.add(rowContent);
}

My tableContent is essentially我的 tableContent 本质上是

"First header", "Second header", "Third header"
"1"           , "2"            , "3"
"1"           , "2"            , "3"
"1"           , "2"            , "3"
"1"           , "2"            , "3"
"1"           , "2"            , "3"

I want to transform it into json as我想把它转换成 json 作为

[{"First header":"1","Second header":"2","Third header":"3"}
, {"First header":"1","Second header":"2","Third header":"3"}
, {"First header":"1","Second header":"2","Third header":"3"}
, {"First header":"1","Second header":"2","Third header":"3"}
, {"First header":"1","Second header":"2","Third header":"3"}]

How do I do this without changing my initial for loop to create my tableContent?如何在不更改初始 for 循环来创建 tableContent 的情况下执行此操作? (since I also need it for doing something else). (因为我也需要它来做其他事情)。

Thank you谢谢

Eko埃科

Your tableContent is not essential to your example.您的 tableContent 对您的示例not必需的。 Your tableContent right now is a List<List<string>> so it will be serialized as您现在的 tableContent 是List<List<string>>因此它将被序列化为

[["First header","Second header","Third header"],["1","2","3"],["1","2","3"],["1","2","3"],["1","2","3"],["1","2","3"]]

If you need to keep your for loop unchanged, then write your own custom serializer .如果您需要保持for循环不变, 请编写您自己的自定义序列化程序。 If you have no need in keeping for loop unchanged, form your data in right way.如果您不需要保持for循环不变,请以正确的方式形成您的数据。 For an example:例如:

var tableContent = new List<dynamic>();

for (int i = 0; i < 5; i++)
{
    var rowContent = new Dictionary<dynamic, dynamic>();
    rowContent["First header"] = "1";
    rowContent["Second header"] = "2";
    rowContent["Third header"] = "3";
    tableContent.Add(rowContent);
}

Will result as:结果如下:

[{"First header":"1","Second header":"2","Third header":"3"},{"First header":"1","Second header":"2","Third header":"3"},{"First header":"1","Second header":"2","Third header":"3"},{"First header":"1","Second header":"2","Third header":"3"},{"First header":"1","Second header":"2","Third header":"3"}]

PS if you have no special purposes, you can change your dynamic to strong types: PS如果没有特殊用途,可以把你的dynamic改成强类型:

var tableContent = new List<Dictionary<string, string>>();

for (int i = 0; i < 5; i++)
{
    var rowContent = new Dictionary<string, string>();
    rowContent["First header"] = "1";
    rowContent["Second header"] = "2";
    rowContent["Third header"] = "3";
    tableContent.Add(rowContent);
}

You can use newtonsoft - Json.NET to build (and parse) jsons.您可以使用newtonsoft - Json.NET来构建(和解析)json。

It can be used in various ways, both "manually" and using automatic serialization.它可以以多种方式使用,包括“手动”和使用自动序列化。 See here: Creating JSON .请参阅此处: 创建 JSON

The code below demonstrates how to use the "manual" approach to build the json in parallel to building your current data structure (like I understood you'd like to do):下面的代码演示了如何使用“手动”方法来构建 json 以并行构建您当前的数据结构(就像我理解您想要做的那样):

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Newtonsoft.Json.Linq;

namespace Test
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<List<string>> tableContent = new List<List<string>>();
            JArray tableJson = new JArray(); // This will be the table json object we will build 

            string[] headerNames = { "First header", "Second header", "Third header" };

            List<string> rowHeader = new List<string>();
            rowHeader.Add(headerNames[0]);
            rowHeader.Add(headerNames[1]);
            rowHeader.Add(headerNames[2]);
            tableContent.Add(rowHeader);

            for (int i = 0; i < 5; i++)
            {
                List<string> rowContent = new List<string>();
                JObject rowJson = new JObject(); // This will be the json for one row

                string[] rowElements = { "1", "2", "3" };
                Debug.Assert(rowElements.Length == headerNames.Length);
                for (int j = 0; j < rowElements.Length; ++j)
                {
                    rowContent.Add(rowElements[j]);
                    rowJson[headerNames[j]] = rowElements[j];   // Add the element to the row json
                }
                tableContent.Add(rowContent);
                tableJson.Add(rowJson); // Add the row json to the table json
            }

            // Here tableJson contains the required json.
            // Convert to string and print:
            string tableJsonString = tableJson.ToString();
            Console.WriteLine(tableJsonString);
        }
    }
}

Output:输出:

[
  {
    "First header": "1",
    "Second header": "2",
    "Third header": "3"
  },
  {
    "First header": "1",
    "Second header": "2",
    "Third header": "3"
  },
  {
    "First header": "1",
    "Second header": "2",
    "Third header": "3"
  },
  {
    "First header": "1",
    "Second header": "2",
    "Third header": "3"
  },
  {
    "First header": "1",
    "Second header": "2",
    "Third header": "3"
  }
]

Note: I changed the dynamic lists to have concrete types as this is more efficient.注意:我将dynamic列表更改为具有具体类型,因为这样更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM