I'm doing a project where I call data using an API and transform it into JSON. I've been able to get that part, but my main problem now is getting it to transform into a readable data file. I'm able to run my function from the command line, but I just get back a huge chunk of data that isn't readable. I need to transform it into a JSON file.
This is different from other C# to json questions because I am not reading the data from a file, I am parsing data from an api source to json.
Can anyone give me some pointers? I've been trying to follow tutorials online, but most of them deal with taking JSON and parsing it through C#, not calling data directly. If anyone has any good tutorials that can accomplish what I need to do, please send them my way.
To give some background, I am trying to pull up tickets for a helpdesk app. The app takes the api URL and writes it to JSON. Now, I just need a way to format the JSON and push it into its own file.
Here is my current code:
using System;
using System.Net;
using System.Text;
using System.IO;
class Program
{
static void Main()
{
string fdDomain = "mydomain";
string apiKey = "12345";
string apiPath = "/api/tickets";
string responseBody = String.Empty;
string myUrl = "https://" + fdDomain + ".freshdesk.com" + apiPath;
Console.WriteLine("myUrl = " + myUrl);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myUrl);
request.ContentType = "application/json";
request.Method = "GET";
string authInfo = apiKey + ":mypassword";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
try
{
Console.WriteLine("Submitting Request");
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
responseBody = reader.ReadToEnd();
reader.Close();
dataStream.Close();
Console.WriteLine("Status Code: {1} {0}", ((HttpWebResponse)response).StatusCode, (int)((HttpWebResponse)response).StatusCode);
}
Console.WriteLine(responseBody);
}
catch (WebException ex)
{
Console.WriteLine("API Error: Your request is not successful. If you are not able to debug this error properly, mail us at support@freshdesk.com with the follwing X-Request-Id");
Console.WriteLine("X-Request-Id: {0}", ex.Response.Headers["X-Request-Id"]);
Console.WriteLine("Error Status Code : {1} {0}", ((HttpWebResponse)ex.Response).StatusCode, (int)((HttpWebResponse)ex.Response).StatusCode);
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.Write("Error Response: ");
Console.WriteLine(reader.ReadToEnd());
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR");
Console.WriteLine(ex.Message);
}
}
}
}