Home > OS >  Create JSON object from dynamic list from C#
Create JSON object from dynamic list from C#

Time:05-17

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

"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

[{"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? (since I also need it for doing something else).

Thank you

Eko

CodePudding user response:

Your tableContent is not essential to your example. Your tableContent right now is a List<List<string>> so it will be serialized as

[["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. If you have no need in keeping for loop unchanged, form your data in right way. 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"}]

P.S. if you have no special purposes, you can change your dynamic to strong types:

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);
}

CodePudding user response:

You can use newtonsoft - Json.NET to build (and parse) jsons.

It can be used in various ways, both "manually" and using automatic serialization. See here: Creating 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):

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.

  • Related