-4
我想將JSON數據導出到CSV文件。我創建了一個函數WriteReportToCSV()來完成這項工作。當我嘗試運行我的程序時,我的代碼沒有讀取該函數。我在代碼中丟失了什麼嗎?如何將JSON對象數據寫入csv文件?
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);
}
}
}
}
你是什麼意思'當我嘗試運行我的程序時,我的代碼沒有讀取函數。 '?你的意思是你忘了叫'HarvestRaken'?或者是其他東西? – mjwills
@mjwills。當我點擊運行時,它開始開始收穫,但隨後它返回(rc == null)並且不寫入writeReporttoCSV()。我的問題是我無法將數據寫入CSV。不明白我在代碼中缺少的是什麼。 – Rck7
@ mjwills.I能夠反序列化對象(sr),沒有例外。你是什麼意思,你忘了分配給結果變量? –
Rck7