首页 > 解决方案 > How to convert list to json in c#

问题描述

I have converted CSV to a list of string I want to create a JSON using the header of CSV file the input and output are as mentioned below

var list = [
    [a,b,c],
    [1,2,3],
    [4,5,6]
    ];

to

var json = { 
        {
            "a":1,
            "b":2,
            "c":3
        },
        {
            "a":4,
            "b":5,
            "c":6
        }
    }

标签: c#

解决方案


Assuming your list looks like

        var list = new string[3][] {
            new string[3] { "a","b","c" },
            new string[3] {"1","2","3" },
            new string[3] {"4","5","6"}
        };

You can make a json from it using this method:

public static string toJson(string[][] csvArray) {
        var sb = new StringBuilder("{\n\"elements\": [\n");
        var headers = new string[csvArray[0].Length];
        
        for(int i = 0; i < csvArray[0].Length; i++)
        {
            headers[i] = csvArray[0][i];
        }
        
        for(int i = 1; i < csvArray.Length; i++)
        {
            sb.AppendLine("{");
            for(int j = 0; j < csvArray[i].Length; j++)
            {
                sb.AppendLine("\"" + headers.ElementAtOrDefault(j) + "\": \"" + csvArray[i][j] + "\",");
            }
            sb.Remove(sb.Length-3, 3); // remove last ",/n" to make json valid
            sb.AppendLine("\n},");
        }
        sb.Remove(sb.Length-3, 3); // remove last ",/n" to make json valid
        sb.AppendLine("\n]\n}");
        
        return sb.ToString();
    }

Check it in fiddler. Some alterations might be needed to adjust to your input data, maybe some additional validations, but it will let you go forward.


推荐阅读