简体   繁体   中英

How to read serialized objects from json file without use File.ReadAllLines? C#

In a lot of examples i have one object and File.ReadAllLines which can be simple deserialized (because this is one object, one string, and we needn't split it. But what can i do with collection of objects?

I have a simple class customer and i would like to serialize list with this kind of objects. For example

var customer = new Customer()
            {
                FirstName = "Luiggi",
                LastName = "Somf",
                Address = "3 Wall St"
            };

List<Customer> list = new List<Customer>();

And there, first question, is there any better way to easier serialize list of objects and write it to file?

StreamWriter writer = new StreamWriter("file.json");

            foreach(Customer cust in list)
            {
                string json = JsonSerializer.Serialize(cust);
                writer.Write(json);
            }

            writer.Close();

And the second, is there easier way to read this collection or single objects from file than read line, split it (maybe using regex), deserialize, and next, add this to list?

StreamReader reader = new StreamReader("file.json");

            string[] jsons;

            while (!reader.EndOfStream)
            {
                jsons = reader.ReadLine().Split('}');
                
            }
            reader.Close();

Thank you very much!

You can serialize the entire list. By simply serializing the list object.

Just write:

JsonSerializer.Serialize(list); Instead of:

JsonSerializer.Serialize(cust);

And get rid of the for loop.

There are a few ways to solve the problem, however I would recommend not serialising individual objects if you want to read/write an entire file at a time.

In the simplest of ways, you can just serialise and deserialise the list, like so:

//Serialise and Save
await File.WriteAllTextAsync("file.json", JsonSerializer.Serialize(list));

//Deserialise
Customers customers = JsonSerializer.Deserialize<List<Customers>>(await File.ReadAllTextAsync("file.json"));

However, there are better, cleaner ways.

Firstly I would recommend modelling the file separately:

public class CustomersFile
{
    public List<Customer> Customers {get; set; }
}
//....

....//
public CustomersFile customersFile = new();

then I would serialise and deserialise this.

//Serialise and Save
await File.WriteAllTextAsync("file.json", JsonSerializer.Serialize(customersFile));

//Deserialise
CustomersFile customersFile = JsonSerializer.Deserialize<CustomersFile>(await File.ReadAllTextAsync("file.json"));

once I'd loaded the file into memory, it's simply a case of using linq to retrieve what you need.

//iterate through the list as normal
foreach(Customer customer in customersFile.Customers)
{
    Console.WriteLine(customer.LastName);
}

//Get the record by name/details
IEnumerable<Customer> foundCustomers = customersFile.Customers.Where(c => c.LastName.Equals("Somf"));

Now, this doesn't solve the "looking through a file to find the correct record", as it involved loading the file into memory and deserialising every time you want to find something, however a few questions:

Why do you need to iterate through the file, not just through the collection?

Why are you using a flat file as storage?

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