简体   繁体   English

ASP.NET 内核 — 上传.json 文件并转换为列表<t></t>

[英]ASP.NET Core — Upload .json file and convert to List<T>

So I managed to export a.json file by serializing my List.所以我设法通过序列化我的列表来导出 a.json 文件。 Now i'm trying to upload a.json file and desearialize it and add it back to my list.现在我正在尝试上传 a.json 文件并将其反序列化并将其添加回我的列表中。 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:这是我的 controller 中的 function 不起作用:

** 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: ** 更新 ** 所以现在我设法将.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");
    }

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.所以我想选择一个文件(用户应该只被允许上传。json 格式除了 idk 怎么做之外别无他法)然后从那个。json 我想将每个条目添加到我的预订列表中。 Here is the Booking Model:这是预订 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:这里是出口 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);
    }

You need to initialize the list, before you are trying to add new items to it.在尝试向其添加新项目之前,您需要初始化列表。

var bookings = new List<Booking>();

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:那是因为如果您在缓存中没有值,它会将值null设置为bookings 。您需要进行如下更改:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM