Rck7 Rck7 - 4 months ago 13
JSON Question

How to write JSON Object data to a csv file?

I am trying to export the JSON data to a CSV file. I have created a function WriteReportToCSV() to do this job. When I try to run my program, my code is not reading the function. Am I missing something in my code?

TestApp.cs:

namespace TestApp
{
class TestApp
{
public List<report> Reports { get; set; }
public List<worklog> worklogs { get; set; }
public List<answer> answers { get; set; }

public void HarvestRaken()
{
var rc = GetReports();

if (rc == null) return;

rc.WriteReportToCSV(@"C:\Projects\TestApp\Report_Data.csv");

}

public string token = "1abcdef3-k89x-3w574-3589-2957c29ki7m1";

public reportcontainer GetReports()
{

Console.WriteLine("Reading Reports");

reportcontainer result = null;

try
{
string url = "https://app.ticketappapp.com/api/v2/reports/?startDate=2017-06-07&endDate=2017-07-07&maxResults=10000&filters=project.id:279658&filters=project.id:279654&filters=project.id:279652";

WebRequest request = WebRequest.Create(url);

request.Method = "GET";
request.Headers.Add("Authorization", "Bearer " + token);

using (WebResponse response = request.GetResponse())
{
using (Stream responstream = response.GetResponseStream())

{
string sr = new StreamReader(responstream).ReadToEnd();

reportcontainer rc = JsonConvert.DeserializeObject<reportcontainer>(sr);
}
}
}

catch (Exception ex)
{

}

return result;
}


Project.cs:

namespace TestApp
{

public class reportcontainer
{
public List<report> reports { get; set; }
public string totalHits { get; set; }

public void WriteReportToCSV(string Filepath)
{

using (var sw = new StreamWriter(Filepath))
{

foreach (report rep in this.reports)

{
sw.WriteLine("Reading Reports:");
sw.WriteLine(" Reading:" + "," + rep.id + "," + rep.status + "," + rep.completed + "," + rep.date);

}

foreach (worklog wl in this.reports.SelectMany(r => r.worklogs))

{
sw.WriteLine("Reading Worklogs:");
sw.WriteLine(" Reading:" + "," + wl.id + "," + wl.subcontractor + "," + wl.hours + "," + wl.workerCount + "," + wl.workdesc);

}

foreach (answer ans in this.reports.SelectMany(r => r.answers))
{
sw.WriteLine("Reading Survey:");
sw.WriteLine(" Reading:" + "," + ans.id + "," + ans.question + "," + ans.questionid + "," + ans.FormattedAnswer + "," + ans.desc);

}

}
}
}

Answer Source
reportcontainer rc = JsonConvert.DeserializeObject<reportcontainer>(sr);

should be changed to:

result = JsonConvert.DeserializeObject<reportcontainer>(sr);

Because you never assign a value to result, it is always null.

Thus WriteReportToCSV is never called.