JSON string to CSV and CSV to JSON conversion in c#
I was able to solve it by DeserializeObject to a datatable using Json.net, so want to post my own answer but will not mark it as accepted, if anyone have better way to do this.
To convert JSON string to DataTable
public static DataTable jsonStringToTable(string jsonContent)
{
DataTable dt = JsonConvert.DeserializeObject<DataTable>(jsonContent);
return dt;
}
To make CSV string
public static string jsonToCSV(string jsonContent, string delimiter)
{
StringWriter csvString = new StringWriter();
using (var csv = new CsvWriter(csvString))
{
csv.Configuration.SkipEmptyRecords = true;
csv.Configuration.WillThrowOnMissingField = false;
csv.Configuration.Delimiter = delimiter;
using (var dt = jsonStringToTable(jsonContent))
{
foreach (DataColumn column in dt.Columns)
{
csv.WriteField(column.ColumnName);
}
csv.NextRecord();
foreach (DataRow row in dt.Rows)
{
for (var i = 0; i < dt.Columns.Count; i++)
{
csv.WriteField(row[i]);
}
csv.NextRecord();
}
}
}
return csvString.ToString();
}
Final Usage in Web API
string csv = jsonToCSV(content, ",");
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StringContent(csv);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "export.csv" };
return result;
c# convert json string to .csv
try with newtonsoft jsonparser.
If you can get your JSON as a string..
dynamic dynObj = JsonConvert.DeserializeObject(jsonString);
string CSV = "";
foreach (var data in dynObj.inputFile)
{
List<string> row = new List<string>();
foreach(var dataItem in data)
{
row.Add(dataItem);
}
CSV+=string.Join(row, ",");
}
You will get 1 giant string containing all the values as a CSV.
Let us know if this is what you want.
C# Convert Json to CSV
With Cinchoo ETL - an open source library, you can do do the conversion easily with few lines of code
string json = @"{
""HDRDTL"":[""SRNO"",""STK_IDN"",""CERTIMG""],
""PKTDTL"":[
{""SRNO"":""2814"",""STK_IDN"":""1001101259"",""CERTIMG"":""6262941723""},
{""SRNO"":""2815"",""STK_IDN"":""1001101269"",""CERTIMG"":""6262941726""},
{""SRNO"":""2816"",""STK_IDN"":""1001101279"",""CERTIMG"":""6262941729""}
],
""IMGTTL"":
[""CERTIMG"",""ARRIMG""],
""IMGDTL"":{""CERTIMG"":""CRd6z2uq3gvx7kk"",""ARRIMG"":""ASd6z2uq3gvx7kk""}
}";
StringBuilder sb = new StringBuilder();
using (var p = ChoJSONReader.LoadText(json).WithJSONPath("$..PKTDTL")
)
{
using (var w = new ChoCSVWriter(sb)
.WithFirstLineHeader()
)
w.Write(p);
}
Console.WriteLine(sb.ToString());
Output:
SRNO,STK_IDN,CERTIMG
2814,1001101259,6262941723
2815,1001101269,6262941726
2816,1001101279,6262941729
Checkout CodeProject article for some additional help.
Disclaimer: I'm the author of this library.
How to convert CSV string to json (or to c# object's list) without loop? using .NET Framework or .NET Core
This can be done using LINQ and Json.Net (but will still do loops internally) :
using Newtonsoft.Json;
using System.Linq;
// -----------
var data = "\"Product\",\"Date\",\"Expiry\",\"Type\",\"Price\":\"ABC\",\"20-Jul-2019\",\"20-Jul-2022\",\"Supplement\",\"1300\":\"XYZ\",\"20-Jul-2019\",\"20-Jul-2022\",\"Supplement\",\"100\":\"AAA\",\"20-Jul-2019\",\"20-Jul-2022\",\"Supplement\",\"200\":\"XXX\",\"20-Jul-2019\",\"20-Jul-2022\",\"Supplement\",\"500\"";
var datas = data.Split(':'); // string[] containing each line of the CSV
var MemberNames = datas[0].Split(','); // the first line, that contains the member names
var MYObj = datas.Skip(1) // don't take the first line (member names)
.Select((x) => x.Split(',') // split columns
/*
* create an anonymous collection
* with object having 2 properties Key and Value
* (and removes the unneeded ")
*/
.Select((y, i) => new { Key = MemberNames[i].Trim('"'),
Value = y.Trim('"') })
// convert it to a Dictionary
.ToDictionary(d => d.Key, d => d.Value));
// MYObject is IEnumerable<Dictionary<string, string>>
// serialize (remove indented if needed)
var Json = JsonConvert.SerializeObject(MYObj, Formatting.Indented);
Debug.WriteLine(Json);
This outputs :
[
{
"Product": "ABC",
"Date": "20-Jul-2019",
"Expiry": "20-Jul-2022",
"Type": "Supplement",
"Price": "1300"
},
{
"Product": "XYZ",
"Date": "20-Jul-2019",
"Expiry": "20-Jul-2022",
"Type": "Supplement",
"Price": "100"
},
{
"Product": "AAA",
"Date": "20-Jul-2019",
"Expiry": "20-Jul-2022",
"Type": "Supplement",
"Price": "200"
},
{
"Product": "XXX",
"Date": "20-Jul-2019",
"Expiry": "20-Jul-2022",
"Type": "Supplement",
"Price": "500"
}
]
Related Topics
Convert Bitmaps to One Multipage Tiff Image in .Net 2.0
Example Using Hyperlink in Wpf
How to Find Fqdn of Local MAChine in C#/.Net
How Would You Make a Unique Filename by Adding a Number
Converting a Generic List to a CSV String
Http 404 Page Not Found in Web API Hosted in Iis 7.5
How to Use Showdialog Without Blocking All Forms
How to Access Configuration in Any Class in ASP.NET Core
Databind the Source Property of the Webbrowser in Wpf
Check If Instance Is of a Type
Implementing Collectionchanged
How Can a Separator Be Added Between Items in an Itemscontrol
How to Monitor Clipboard Content Changes in C#