I’m trying to create two method to serialize/deserialize classes using Json.Net and save/load them to/from file and this is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
namespace System
{
public static class SystemExtentions
{
public static void SaveToFile(this object data, string FileName)
{
using (StreamWriter writer = new StreamWriter(FileName))
{
string s = JsonConvert.SerializeObject(data);
writer.Write(s);
writer.Close();
}
}
public static void LoadFromFile<t>(t date,string FileName)
{
using (StreamReader reader = new StreamReader(FileName))
{
data = JsonConvert.DeserializeObject<t>(reader.ReadToEnd());
reader.Close();
}
}
}
}
but in LoadFromFile method data = JsonConvert.DeserializeObject<t>(reader.ReadToEnd()); doesn’t work! it means that if I had this code:
Class1 c1=new Class1();
c1.LoadFromFile<Class1>("c1.clf");
after the code runs the properties of c1 doesn’t change.
I want to Know why and is there any solution to modify the class or set it’s properties(deserialize it!) from LoadFromFile in independent(independent to class type and properties)(dynamically) way?
Your LoadFromFile method takes a parameter of type
tthat your are assigning to inside the method. This does not make sense. Instead, use a return value:This would allow you to use this code like this:
Side note: no need to explicitly close a streamreader if you use the
usingconstruct