0

So I managed to export a .json file by serializing my List. Now i'm trying to upload a .json file and desearialize it and add it back to my list. The idea is to be able to click on import, choose a file, then convert it so i can add it to my list. Here is the function in my controller that doesn't work:

** Update ** So now I managed to convert the .json file back to my List but if the list is empty and I want to add the new list to it, then I get this error:

enter image description here

[HttpPost]
    public async Task<IActionResult> Import(IFormFile file)
    {
        if (file == null || file.Length == 0)
            return Content("file not selected");

        var path = Path.Combine(Directory.GetCurrentDirectory(), "Import", file.FileName);

        using (var stream = new FileStream(path, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }

        String jsonImport = System.IO.File.ReadAllText(path);
        Console.WriteLine(jsonImport);
        List<Booking> bookings;
        _cache.TryGetValue("key", out bookings);
        List<Booking> newList = new List<Booking>();

        newList = JsonConvert.DeserializeObject<List<Booking>>(jsonImport);

        foreach (var item in newList)
        {
            bookings.Add(item);
            _cache.Set<List<Booking>>("key", bookings);
        }
        return RedirectToAction("Index");
    }

So I want to choose a file (user should only be allowed to upload .json format nothing else but idk how to do that yet) and then from that .json I want to add every entry to my bookings List. Here is the Booking Model:

public class Booking
{
    [Required]
    [Display(Name = "Ladestand")]
    [Range(0, 100)]
    public double chargeState { get; set; }

    [Required]
    [Display(Name = "Benötigte Fahrstrecke")]
    [Range(1, 1000)]
    public double distance { get; set; }

    [Required]
    [Display(Name = "Beginn")]

    public DateTime startTime { get; set; }

    [Required]
    [Display(Name = "Ende")]

    public DateTime endTime { get; set; }

    [Required]
    [Display(Name = "Anschlusstyp")]
    [EnumDataType(typeof(ConnectorType))]
    public ConnectorType connectorType { get; set; }
}

And here is the export function:

public ActionResult Export()
    {
        string fileName = "BookingsExport.json";
        List<Booking> bookingsList;
        _cache.TryGetValue("key", out bookingsList);

        string json = JsonConvert.SerializeObject(bookingsList);
        FileInfo file = new FileInfo(fileName);
        using (StreamWriter writer = file.CreateText())
        {
            writer.Write(json);
        }

        byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);

        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Json, fileName);
    }
5
  • function in my controller that doesn't work is not a description of your problem. Do you have an error message to share? Commented May 28, 2020 at 19:31
  • Sorry my bad: Error CS0266 Cannot implicitly convert type 'object' to 'System.Collections.Generic.List<WebApplication.Models.Booking>'. An explicit conversion exists (are you missing a cast?) Commented May 28, 2020 at 19:39
  • So basically the problem is with the newList = JsonConvert.DeserializeObject(jsonImport); I don't know how to convert the .json file back to List<Booking> Commented May 28, 2020 at 19:40
  • 1
    Try with JsonConvert.DeserializeObject<List<Booking>> Commented May 28, 2020 at 19:43
  • ok i'm a bit confused like it seemed to work, BUT...if i open the web application, my list is empy by default then i import a list it doesn't work. If i add something to my list so that it's not empty before importing then it works. how can i add a png file to show you the problem ? Commented May 28, 2020 at 19:48

2 Answers 2

1

You need to initialize the list, before you are trying to add new items to it.

var bookings = new List<Booking>();
Sign up to request clarification or add additional context in comments.

Comments

1

That is because if you do not has value in the cache,it would set the value null to the bookings.You need to change like below:

List<Booking> bookings;
var flag = _cache.TryGetValue("key", out bookings);
if(!flag)
{
    bookings = new List<Booking>();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.