我正在尝试将JSON数据导出到CSV文件。我创建了一个函数WriteReportToCSV()来完成这项工作。当我尝试运行我的程序时,我的代码没有读取该函数。我在代码中遗漏了什么吗?
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);
}
}
}
}
答案 0 :(得分:0)
reportcontainer rc = JsonConvert.DeserializeObject<reportcontainer>(sr);
应更改为:
result = JsonConvert.DeserializeObject<reportcontainer>(sr);
因为您从未为result
分配值,所以总是为空。
因此永远不会调用WriteReportToCSV
。