首页 > 解决方案 > ASP.NET Core -- 上传 .json 文件并转换为 List

问题描述

所以我设法通过序列化我的列表来导出一个 .json 文件。现在我正在尝试上传一个 .json 文件并将其反序列化并将其添加回我的列表中。这个想法是能够单击导入,选择一个文件,然后将其转换,以便我可以将其添加到我的列表中。这是我的控制器中不起作用的功能:

** 更新 ** 所以现在我设法将 .json 文件转换回我的列表,但是如果列表为空并且我想将新列表添加到其中,那么我会收到此错误:

在此处输入图像描述

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

所以我想选择一个文件(用户应该只允许上传 .json 格式,除了 idk 怎么做)然后我想从那个 .json 中将每个条目添加到我的预订列表中。这是预订模型:

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; }
}

这是导出功能:

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

标签: c#jsonasp.net-mvcasp.net-coremodel-view-controller

解决方案


在尝试向其添加新项目之前,您需要初始化列表。

var bookings = new List<Booking>();

推荐阅读