简体   繁体   中英

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. Here is what it looks like


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

And SparkPostTemplateDetailModel:

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

How can I save to JSON file each Id I got from an API?

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]

I want it to look like this:

Id1
Id2
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.

Your code is almost there, you just need to take each element in your list and append it to your file:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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