将动态csv转换为包含List< string>的json. C# [英] Convert dynamic csv to json containing List<string> C#

查看:101
本文介绍了将动态csv转换为包含List< string>的json. C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想序列化C#中的字符串列表?以前,我已经成功地使用了开源库Cinchoo ETL来完成类似的任务,但是我陷入了这种特殊情况.我不想使用POCO,因为我的源数据结构是动态的.我宁愿从csv中读取数据并对其进行序列化.

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.

我的csv格式的源数据:

My source data in csv format:

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

必需的输出JSON-{"id":1,"name":"Tom","friends":["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());

输出:

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

这篇关于将动态csv转换为包含List< string>的json. C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆