0

below is the code where i am not able to write the data to json format in txt/json file. it is adding as a string. please help, how can i add the data to txt/json file from rest api output. what changes is require.

using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;

namespace ConsoleApp2
{

public class Class1
{
    private const string URL = "http://api.aladhan.com/calendar?latitude=51.5073509&longitude=-0.1277583&timezonestring=Europe%2FLondon&method=2&month=03&year=2016";


    static void Main(string[] args)
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(URL);

        // Add an Accept header for JSON format.
        client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

        // List data response.
        HttpResponseMessage response = client.GetAsync(URL).Result;  // Blocking call!
        if (response.IsSuccessStatusCode)
        {
            // Parse the response body. Blocking!
            var dataObjects = response.Content.ReadAsStringAsync().Result ; //.ReadAsAsync<IEnumerable<DataObject>>().Result;
            string ab = JsonConvert.SerializeObject(dataObjects.ToString(), Formatting.Indented);


            using (StreamWriter file = File.CreateText(@"e:\path.txt"))
            {
                JsonSerializer serializer = new JsonSerializer();
                //serialize object directly into file stream
                serializer.Serialize(file, ab);
            }
        }
        else
        {
            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
        }
    }

    }
}
Farhan
  • 91
  • 1
  • 12
  • 1
    You are downloading the result as a string -- `ReadAsStringAsync().Result` -- then serializing that string to another string, then writing that second string to the file. So of course it will be escaped. Why not just write the downloaded string directly to the file? What are you trying to accomplish? – dbc Nov 18 '17 at 03:14
  • i used var dataObjects = response.Content.ReadAsStringAsync().Result; and added the data to file. but while retrieving the data it is giving me errorvar jsonText = File.ReadAllText(@"e:\path.txt"); var sponsors = JsonConvert.DeserializeObject>(jsonText); InnerException {"Could not cast or convert from System.String to System.Collections.Generic.IList`1[ConsoleApp2.Class1+date]."} System.Exception {System.ArgumentException} – Farhan Nov 18 '17 at 03:20
  • I'm note sure why you have such complicated code to write string to file (so I believe it is just duplicate of basic [write text to file](https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file) ). If you are looking for something else - [edit] post to clarify why it is not enough and what exactly you want to achieve. – Alexei Levenkov Nov 18 '17 at 03:21
  • 1
    Are you trying to take an unindented JSON string and write it to a file with indentation? If so see [this specific answer here](https://stackoverflow.com/questions/2661063/how-do-i-get-formatted-json-in-net-using-c/30329731#30329731), only write to a `StreamWriter` instead of a `StringWriter`. Otherwise we need an [mcve] that actually demonstrates your real problem. – dbc Nov 18 '17 at 03:25
  • Alexei Levenkon , it is not writing the code to text file. i want to achieve by writing the output to json format to a file. which is not happening in this case it is writing output as string. so can you provide me the solution how to write string to a file which is formatted as json. while reading the file it should properly read as json. – Farhan Nov 18 '17 at 03:29
  • `dataObjects` is string containing JSON, if you just write that to file you achieve what the post seem to be asking. I'd recommend you to re-read question you've posted and make sure it actually demonstrate problem you are facing (based on previous comment you don't know how to write syntactically correct call to deserialize from string to object, which has absolutely nothing to do with question as posted). Also check out [MCVE] guidance and try to use inline constatnts (like `"{\"a\":1}"`) to show values instead of calls to random service. – Alexei Levenkov Nov 18 '17 at 03:36
  • Side note: if you planning to ping someone in comments you need to add `@` in front of the name (which also provide autocomplete for names you can ping) – Alexei Levenkov Nov 18 '17 at 03:37
  • @AlexeiLevenkov thanks for pointing me to correct direction. i am sorry i am not able to explain the problem properly. – Farhan Nov 18 '17 at 04:15

0 Answers0