Home > Software engineering >  How to write list values from a model to a C# file?
How to write list values from a model to a C# file?

Time:09-09

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!

CodePudding user response:

Trying to transform a list to string wont tell you anithing 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();
    var fileName = "response.json";

    //AppendText will create a new file, if the file doesn't exist already
    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

CodePudding user response:

So, you are invoking the ToString() method of List<T> class. Which converts the intended object to its string representation. It won't contain the values that you have in the objects, well, unless you have a custom List implementation and you override the ToString() method.

If you have c# objects that you want to get as a JSON string, then you could use a Newtonsoft.Json to get it as a JSON string. Something like this:

File.WriteAllText(@"C:\temp\Response.json", JsonConvert.SerializeObject(test));
  • Related