Asp.Net core Web API: how can I export and import JSON from the external REST APIs?

Viewed 32

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);
    }
0 Answers
Related