c# - 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);
}
解决方案
在尝试向其添加新项目之前,您需要初始化列表。
var bookings = new List<Booking>();
推荐阅读
- perl - 如何在 Perl 中将总线一元化和/减少一点?
- python - 如何在python Tkinter程序中将变量参数传递给MYSQL数据库查询
- java - Springboot 应用程序已启动,但 POST 请求始终返回“未找到”
- bash - find 列出的文件列表的 md5sum
- angular - 如何在 *ngfor 项目中单击按钮时显示单独的事件?
- jenkins - 如何在管道的下游作业中获取上游作业已运行的节点名称
- ios - 了解 Apple 远程收据
- javascript - 验证完成后,Nestjs 将函数应用于每个控制器函数/路由
- vulkan - 为什么有些命令只能在渲染通道之外记录?
- keras - (深度学习,rnn,cnn)图像图像 captinoing 与 keras