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:
[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);
}
