【发布时间】:2017-12-22 01:38:28
【问题描述】:
我正在尝试将 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;
}
项目.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);
}
}
}
}
【问题讨论】:
-
When I try to run my program, my code is not reading the function.是什么意思?你的意思是你忘了打电话给HarvestRaken?还是别的什么? -
@mjwills。当我点击 Run 时,它开始收割,但随后返回 (rc == null) 并且没有 writeReporttoCSV()。我的问题是我无法将数据写入 CSV。不明白我的代码中缺少什么。
-
@mjwills.我能够成功反序列化对象
(sr),没有例外。你是什么意思,你刚刚忘记给结果变量赋值?