0

我试图将 CSV 数据转换为 JSON。它安静地工作得很好,但很少有列有逗号,在转换为 json 时,逗号包含的数据被拆分。这是我试过的代码,

var path = @"C:xyz\\abc.csv";
            var csv = new List<string[]>();
            var lines = File.ReadAllLines(path);

            foreach (string line in lines)
                csv.Add(line.Split(','));

            var properties = lines[0].Split(',');

            var listObjResult = new List<Dictionary<string, string>>();

            for (int i = 1; i < lines.Length; i++)
            {
                var objResult = new Dictionary<string, string>();
                for (int j = 0; j < properties.Length; j++)
                    objResult.Add(properties[j], csv[i][j]);

                listObjResult.Add(objResult);
            }
            var json = JsonConvert.SerializeObject(listObjResult, Formatting.Indented);
            List<ABCModel> desrilize = JsonConvert.DeserializeObject<List<ABCModel>>(json);
            return desrilize;

CSV 数据

employee,emp city,state,emp address
"abc","efg","lkj","building name"
"wer","sdf","qwe","afj Building, near cross"

在上面的第三行中包含逗号,在转换为 json 时不应拆分。在使用上面的代码时,它会被拆分。请帮忙。

在“emp city”中也有一个空间,如何在创建模型时为其定义jsonProperty。

预期的 json

[
  {
    "employee": "abc",
    "emp city": "efg",
    "state": "lkj",
    "emp address": "building name"
  },
  {
    "employee": "wer",
    "emp city": "sdf",
    "state": "qwe",
    "emp address": "afj Building, near cross"
  }
]

先感谢您。

4

3 回答 3

0

您可以尝试使用csvHelpercsv转换器。使用 csv:

var options = new CsvOptions // Defaults
            {
                RowsToSkip = 0, // Allows skipping of initial rows without csv data
                SkipRow = (row, idx) => string.IsNullOrEmpty(row) || row[0] == '#',
                Separator = '\0', // Autodetects based on first row
                TrimData = false, // Can be used to trim each cell
                Comparer = null, // Can be used for case-insensitive comparison for names
                HeaderMode = HeaderMode.HeaderPresent, // Assumes first row is a header row
                ValidateColumnCount = true, // Checks each row immediately for column count
                ReturnEmptyForMissingColumn = false, // Allows for accessing invalid column names
                Aliases = null, // A collection of alternative column names
                AllowNewLineInEnclosedFieldValues = false, // Respects new line (either \r\n or \n) characters inside field values enclosed in double quotes.
                AllowBackSlashToEscapeQuote = false, // Allows the sequence "\"" to be a valid quoted value (in addition to the standard """")
                AllowSingleQuoteToEncloseFieldValues = false, // Allows the single-quote character to be used to enclose field values
                NewLine = Environment.NewLine // The new line string to use when multiline field values are read (Requires "AllowNewLineInEnclosedFieldValues" to be set to "true" for this to have any effect.)
            };

            var csv = File.ReadAllText(fileName or filePath);
            foreach (var line in CsvReader.ReadFromText(csv, options))
            {
                yourModel.Add(new yourModel()
                {
                    StoneCode = line["Field1"],
                    StoneTypeName = line["Field2"],
                });
            }
于 2022-02-17T07:10:47.327 回答
0

这是列表中的另一个,Cinchoo ETL - 一个开源库可以将 CSV 快速转换为 JSON,如下所示

string csv = @"employee,emp city,state,emp address
""abc"",""efg"",""lkj"",""building name""
""wer"",""sdf"",""qwe"",""afj Building, near cross""";

using (var r = ChoCSVReader.LoadText(csv)
       .WithFirstLineHeader()
       .MayHaveQuotedFields()
      )
{
    using (var w = new ChoJSONWriter(Console.Out))
    {
        w.Write(r);
    }
}

输出:

[
  {
    "employee": "abc",
    "emp city": "efg",
    "state": "lkj",
    "emp address": "building name"
  },
  {
    "employee": "wer",
    "emp city": "sdf",
    "state": "qwe",
    "emp address": "afj Building, near cross"
  }
]

小提琴示例:https ://dotnetfiddle.net/Dk4vtO

于 2022-02-18T17:55:02.280 回答
0

要使用 CsvHelper 读取所需的 CSV 输入,此示例应该可以帮助您:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using CsvHelper;
using CsvHelper.Configuration;

public class Program
{
    public static void Main()
    {
        var csvContent = @"employee,emp city,state,emp address
""abc"",""efg"",""lkj"",""building name""
""wer"",""sdf"",""qwe"",""afj Building, near cross""";

        List<Employee> employees;
        using (var reader = new StringReader(csvContent))
        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {
            csv.Context.RegisterClassMap<EmployeeMap>();
            var records = csv.GetRecords<Employee>();
            employees = records.ToList();
        }

        foreach (var employee in employees)
        {
            Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(employee));
        }
    }
}

public class EmployeeMap : ClassMap<Employee>
{
    public EmployeeMap()
    {
        Map(e => e.Name).Name("employee");
        Map(e => e.City).Name("emp city");
        Map(e => e.State).Name("state");
        Map(e => e.Address).Name("emp address");
    }
}

public class Employee
{
    public string Name { get; set; }

    public string City { get; set; }

    public string State { get; set; }

    public string Address { get; set; }
}
于 2022-02-17T10:22:25.833 回答