简体   繁体   中英

Serialize a c# class to a json text file (Newtonsoft)

I have a class setup like the below:

    public class Email
    {
        public int EmailID {get, set}
        public string EmailSubject {get, set}
        public string EmailSender {get, set}
        public string EmailContent {get, set}

    }

Any created instances of this class are stored in this class list:

    public class EmailList
    {
        private List<Email> _list = new List<Email>();

        public void add(Email newEmail)
        {
            _list.Add(newEmail);
        }
    }

I'm wanting to serialize the class list to json and output that to a txt file on my desktop using Newtonsoft on a button click, would anyone be able to show me how to do this?

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
           //export class list to json txt file
        }

try this

 var emailList = new List<Email> { new Email{ EmailID=1, EmailSubject="subject" }};

    var json= System.Text.Json.JsonSerializer.Serialize(emailList);

    StreamWriter  sw;

    string path = @"C:\...yourtpath.. \test.json";
    
    if (!File.Exists(path))
    {
        sw = File.CreateText(path);
    }
    else
    {
        sw = new StreamWriter(path, false);
    }
    
    using (sw)
    {
            sw.WriteLine(json);
    };

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