将.csv文件完全转换为Json数据并过滤JSON数据

时间:2019-04-10 07:46:24

标签: c# json

for (int i = 1; i < lines.Length; i++) {
  var objResult = new Dictionary<string, string>();

  for (int j = 0; j < props.Length; j++) {
    objResult.Add(props[j], csv[i][j]);
    listObjResult.Add(objResult);
  }

  string FINALJSON = JsonConvert.SerializeObject(listObjResult);
}

我做了从csv到json的转换。 JSON数据的输出在FINALJSON中。现在,从FINALJSON中,我只需要获取必填字段。


这是我的数据:

[{"Ccsv":"S124","Profit":"1240025","Cost_Center_Code":"124002503","Description":"test","Status":"","Responsible_Person_Owner":"20041882"},{"Ccsv":"S136","Profit":"1360007","Cost_Center_Code":"136000799","Description":"Default Payroll","Status":"","Responsible_Person_Owner":"SSC"},{"Ccsv":"S800","Profit":"8000001","Cost_Center_Code":"800000201","Description":"SercoCaledonianSl2","Status":"","Responsible_Person_Owner":"20120730"},{"Ccsv":"s802","Profit":"8000002","Cost_Center_Code":"8.00E+58","Description":"sdfergfertxzfcx","Status":"","Responsible_Person_Owner":"3641212"}\]

我只需要获取csv和Profit列。

2 个答案:

答案 0 :(得分:0)

您的JSON似乎是一个对象数组,并且您只想从其中检索两个字段,因此可以尝试以下代码,

string json = FINALJSON;

JArray jArray = JArray.Parse(json);

var result = jArray.Select(x => new { Ccsv = x["Ccsv"], Profit = x["Profit"] }).ToList();

JArray outputJArray = JArray.FromObject(result);

//---------------Print result to console---------------

Console.WriteLine(outputJArray.ToString());

注意:您需要从程序包管理器控制台添加newtonsoft.json nuget程序包,然后将using Newtonsoft.Json.Linq;命名空间导入程序。

输出:

enter image description here

答案 1 :(得分:-1)

我希望它对您有用。

JObject obj = JObject.Parse(json);
var ccsv=obj.SelectToken("Ccsv");
var profit=obj.SelectToken("Profit");