2

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"]}

Cinchoo
  • 6,088
  • 2
  • 19
  • 34
sonofpaul
  • 25
  • 6
  • The title and the content of the question confuse me. Do you want convert CSV to JSON or JSON to CSV? – Pac0 May 10 '20 at 19:18
  • https://stackoverflow.com/questions/60855584/csv-to-nested-json-c-sharp?noredirect=1&lq=1 – Jabberwocky May 10 '20 at 19:24
  • @Pac0 - I want to convert csv to json. However, since my source data structure is dynamic I will not use POCO. My eventual json format is what I have mentioned in the question. I am trying to understand if there are any opensource libraries so that I don't have to reinvent the wheel – sonofpaul May 10 '20 at 19:33
  • @Jabberwocky - slightly different requirement here - I just want a list of strings in the array - no attribute names required within the array. – sonofpaul May 10 '20 at 19:34

1 Answers1

2

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"
 ]
}
Cinchoo
  • 6,088
  • 2
  • 19
  • 34