简体   繁体   中英

Convert dynamic csv to json containing List<string> C#

I want to serialize a list of strings in C#? I have previously successfully used an open-source library Cinchoo ETL for similar tasks, but I am stuck in this particular scenario. I do not want to use POCO since my source data structure is dynamic. I would much rather read the data from a csv and serialize it.

My source data in csv format:

id,name,friends/0,friends/1
1,Tom,Dick,Harry

Required output JSON - {"id":1,"name":"Tom","friends":["Dick","Harry"]}

Here you go, you can do with Cinchoo ETL as below

string csv = @"id,name,friends/0,friends/1
1,Tom,Dick,Harry";

StringBuilder json = new StringBuilder();
using (var w = new ChoJSONWriter(json)
    .Configure(c => c.SupportMultipleContent = true)
    .Configure(c => c.SingleElement = true)
    )
{
    using (var r = ChoCSVReader.LoadText(csv).WithFirstLineHeader()
        .Configure(c => c.AutoArrayDiscovery = true)
        .Configure(c => c.ArrayIndexSeparator = '/')
        )
        w.Write(r);
}
Console.WriteLine(json.ToString());

Output:

{
 "id": "1",
 "name": "Tom",
 "friends": [
  "Dick",
  "Harry"
 ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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