简体   繁体   English

如何将列表值从 model 写入 C# 文件?

[英]How to write list values from a model to a C# file?

I have a model to which the response from the API is written.我有一个 model ,其中写入了来自 API 的响应。 Here is what it looks like这是它的样子


    public class SparkPostTemplateModel
    {
        public List<SparkPostTemplateDetailModel> Results { get; set; }
    }

And SparkPostTemplateDetailModel:和 SparkPostTemplateDetailModel:

    public class SparkPostTemplateDetailModel
    {
        public string Id { get; set; }
    }

How can I save to JSON file each Id I got from an API?如何将我从 API 获得的每个 ID 保存到 JSON 文件?

This Is what I have got:这就是我得到的:



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

And what my program save to file: System.Collections.Generic.List`1[Test.API.Client.Infrastructure.Models.SparkPostTemplateDetailModel]以及我的程序保存到文件的内容:System.Collections.Generic.List`1[Test.API.Client.Infrastructure.Models.SparkPostTemplateDetailModel]

I want it to look like this:我希望它看起来像这样:

Id1编号1
Id2 ID2
Id3 ID3

Thanks for any tips!感谢您的任何提示!

Trying to transform a list to string wont tell you anything about it's contents.尝试将列表转换为字符串不会告诉您有关其内容的任何信息。 What if the list contains complex objects?如果列表包含复杂对象怎么办? what if the list contains more lists?如果列表包含更多列表怎么办? That could get really confusing, so generic list only show you the most basic information about them when transforming them to strings.这可能会变得非常混乱,因此通用列表仅在将它们转换为字符串时向您显示有关它们的最基本信息。

Not sure why you are calling JsonSerializer.SerializeAsync, your wanted result isn't really a valid json file, more like a plain text file.不知道你为什么要调用 JsonSerializer.SerializeAsync,你想要的结果并不是一个有效的 json 文件,更像是一个纯文本文件。

Your code is almost there, you just need to take each element in your list and append it to your file:您的代码几乎就在那里,您只需要将列表中的每个元素和 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;
}

This should work这应该工作

Edit - File per loop编辑 - 每个循环的文件

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.

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