[英]How to write list values from a model to a C# file?
我有一个 model ,其中写入了来自 API 的响应。 这是它的样子
public class SparkPostTemplateModel
{
public List<SparkPostTemplateDetailModel> Results { get; set; }
}
和 SparkPostTemplateDetailModel:
public class SparkPostTemplateDetailModel
{
public string Id { get; set; }
}
如何将我从 API 获得的每个 ID 保存到 JSON 文件?
这就是我得到的:
private SparkPostTemplateModel EmailTemplates { get; set; } = new();
public async Task SaveTemplate()
{
try
{
EmailTemplates = await SparkPostManager.GetTemplates();
var test = EmailTemplates.Results.ToList();
string fileName = "response.json";
using FileStream createStream = File.Create(fileName);
await JsonSerializer.SerializeAsync(createStream, EmailTemplates);
await createStream.DisposeAsync();
File.WriteAllText(@"C:\temp\Response.json", test.ToString());
Console.WriteLine(File.ReadAllText(fileName));
}
catch (Exception ex)
{
throw;
}
以及我的程序保存到文件的内容:System.Collections.Generic.List`1[Test.API.Client.Infrastructure.Models.SparkPostTemplateDetailModel]
我希望它看起来像这样:
编号1
ID2
ID3
感谢您的任何提示!
尝试将列表转换为字符串不会告诉您有关其内容的任何信息。 如果列表包含复杂对象怎么办? 如果列表包含更多列表怎么办? 这可能会变得非常混乱,因此通用列表仅在将它们转换为字符串时向您显示有关它们的最基本信息。
不知道你为什么要调用 JsonSerializer.SerializeAsync,你想要的结果并不是一个有效的 json 文件,更像是一个纯文本文件。
您的代码几乎就在那里,您只需要将列表中的每个元素和 append 放到您的文件中:
private SparkPostTemplateModel EmailTemplates { get; set; } = new();
public async Task SaveTemplate()
{
try
{
EmailTemplates = await SparkPostManager.GetTemplates();
var test = EmailTemplates.Results.ToList();
await using (StreamWriter w = File.AppendText(fileName))
//loop through the list elements and append lines
foreach (var template in test)
{
w.WriteLine(template.Id);
}
Console.WriteLine(File.ReadAllText(fileName));
}
catch (Exception ex)
{
throw;
}
这应该工作
编辑 - 每个循环的文件
private SparkPostTemplateModel EmailTemplates { get; set; } = new();
public async Task SaveTemplate()
{
try
{
EmailTemplates = await SparkPostManager.GetTemplates();
var test = EmailTemplates.Results.ToList();
//AppendText will create a new file, if the file doesn't exist already
//insead of a foreach loop, do a regular for loop, so we can track the index of our elements
for (int i = 0; i < test.Count; i++)
{
//use the index to name the file (add plus one, so the numeration starts with the number one)
await using (StreamWriter w = File.AppendText($"file{i + 1}.txt"))
//retrieve the object from the list using our index
w.WriteLine(test[i].Id);
}
}
catch (Exception ex)
{
throw;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.