Morten Toudahl
Morten Toudahl

Reputation: 640

Casting a deserialized object

I have a PersistenceHandler, which implements different types of persistence (at least it is going to) However, i ran into some problems loading from a file.

Code from PersistenceHandler:

static public object Load(string fileName)
{
    return _persistence.Load(fileName);
}

Which uses this method from JsonPersistence:

public object Load(string fileName)
{
    string readAllText = File.ReadAllText(fileName);    
    return JsonConvert.DeserializeObject<Dictionary<EnumCategories, CategoryViewModel>>(readAllText);    
}

This works fine. As long as i want to serialize to the specified type. But when i want to use it for any type of object, i cant make it work. I have tried using declaring the type as object instead, and then cast it at its 'destination'

Like so:

Employees = (List<EmployeeModel>)PersistenceHandler.Load(_fileName);

I get a casting exception (I am ofc loading the json that contains the correct information)

Additional information: Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'System.Collections.Generic.List`1[KanbanBoard.Model.EmployeeModel]'.

The only way i can get it to work is either by casting it where i deserialize it in my JsonPersistence class, or using the newtonsoft classes to convert it back and forth, at the destination point (like the example above.

Which would be fine - except i am trying really hard to make my program as easy to add features to as possible.

My entire project on github: https://github.com/Toudahl/KanbanBoard EDIT: I am currently working in the refactoring branch

Upvotes: 0

Views: 3014

Answers (1)

EZI
EZI

Reputation: 15364

You can change your method as

public T Load<T>(string fileName)
{
    string readAllText = File.ReadAllText(fileName);
    return JsonConvert.DeserializeObject<T>(readAllText);
}

Now it can be used like:

Employees = PersistenceHandler.Load<List<EmployeeModel>>(_fileName);

Upvotes: 4

Related Questions