1

ASP.Net Core WebAPI is being built to fetch JSON from external REST API endpoint. I would like to save the JSON and reload it

At present, I am fetching the JSON from an external REST API endpoint using the following code:

    public async Task<List<Weather>> Get(string cities)
    {
        List<Weather> weathers = new List<Weather>(); 
        var options = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };

        foreach (var city in cities.Split(";"))
        {
            string APIURL = $"?key={this.apiKey}&q={city}";
            var response = await _httpClient.GetAsync(APIURL);

            if (response.IsSuccessStatusCode)
            {
                var responses = await response.Content.ReadAsStreamAsync();
                var weather = await JsonSerializer.DeserializeAsync<Weather>(responses, options);

                weathers.Add(weather);
            }

        }

        return weathers;
    }

that returns the following JSON

[
   {
      "location":{
         "name":"Chennai",
         "region":"Tamil Nadu",
         ...
      },
      "current":{
         "last_updated_epoch":1663601400,
         "last_updated":"2022-09-19 21:00",
         ...
      }
   },
   {
      "location":{
         "name":"Mumbai",
         "region":"Maharashtra",
         ..
      },
      "current":{
         "last_updated_epoch":1663602300,
         "last_updated":"2022-09-19 21:15",
         ..
      }
   }
]

How can I export and import JSON ?

Update: I have updated the code as mentioned below

public static class JsonFileUtils
{
    private static readonly JsonSerializerSettings _options
        = new() { NullValueHandling = NullValueHandling.Ignore };

    public static void StreamWrite(object obj, string fileName)
    {
        using var streamWriter = File.CreateText(fileName);
        using var jsonWriter = new JsonTextWriter(streamWriter);

        JsonSerializer.CreateDefault(_options).Serialize(jsonWriter, obj);
    }

    public static async Task StreamWriteAsync(object obj, string fileName)
    {
        await Task.Run(() => StreamWrite(obj, fileName));
    }
}

and used it like

    public async Task<List<Weather>> Get(string cities)
    {
        List<Weather> weathers = new List<Weather>(); 
        var options = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };

        foreach (var city in cities.Split(";"))
        {
            string APIURL = $"?key={this.apiKey}&q={city}";
            var response = await _httpClient.GetAsync(APIURL);

            if (response.IsSuccessStatusCode)
            {
                var responses = await response.Content.ReadAsStreamAsync();
                var weather = await JsonSerializer.DeserializeAsync<Weather>(responses, options);

                weathers.Add(weather);
            }

        }

        var fileName = "weathers.json";
        await JsonFileUtils.StreamWriteAsync(weathers, fileName);

        return weathers;
    }

to upload the file

    [HttpPost("upload", Name = "upload")]
    [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(List<Weather>))]
    [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> UploadFile(
            IFormFile file,
            CancellationToken cancellationToken)
    {
        string fileContent = null;

        using (var reader = new StreamReader(file.OpenReadStream()))
        {
            fileContent = reader.ReadToEnd();
        }
        var result = JsonConvert.DeserializeObject<List<Weather>>(fileContent);
        return Ok(result);
    }
One Developer
  • 99
  • 5
  • 43
  • 103
  • "Export" and "import" in what way? JSON itself is just a string, and you've deserialized it to your `Weather` object(s). Do you just want to save that data somewhere, like in a database? Have you tried saving your data somewhere? What didn't work? – David Sep 19 '22 at 16:04
  • @David, The JSON file needs to be saved on the local machine, and another endpoint needs to accept the file. It may be straight forward, but I'm not sure. – One Developer Sep 19 '22 at 16:32
  • 1
    So you want to write `responses` to a file? It looks like that's just a `Stream`, are you just looking for [how to write a Stream to a file](https://stackoverflow.com/q/411592/328193)? – David Sep 19 '22 at 16:36
  • @David, Thank you, Could you please check the update section in the question? It works, but is it okay? – One Developer Sep 19 '22 at 17:29

0 Answers0