Home > Software engineering >  problem loading json to an object list in c#
problem loading json to an object list in c#

Time:10-25

I have a problem loading a JSON file to my object list, I have a program that stores vehicles such as cars etc. and I want to save it down to a JSON file and load the JSON file back up when I start the program again so the stored vehicles are loading in the packing list again. It stores to the list but when I load the program again it would not fill the List vehicles = new List(100);

EDIT:It will save the vehicles but it will not store it to the list when running the program again

public static void ReadParkingFile()          
    {

        string path = @"../../../Configfile/ParkingList.json";
        string jsonText = File.ReadAllText(path);
         List<Vehicle> data = JsonConvert.DeserializeObject<List<Vehicle>>(jsonText).ToList();
       

    }
   
    public static void SaveToJasonFile(string vehicle)
    {
        string path = @"../../../Configfile/ParkingList.json";
         vehicle = JsonConvert.SerializeObject(ParkingHouse.vehicles);
        File.WriteAllText(path, vehicle);


    }

CodePudding user response:

It seems you just need to assign the data reference to ParkingHouse.vehicles

string path = @"../../../Configfile/ParkingList.json";
string jsonText = File.ReadAllText(path);
List<Vehicle> data = JsonConvert.DeserializeObject<List<Vehicle>>(jsonText).ToList();  
ParkingHouse.vehicles = data; // <- here
  • Related