This serializer has some nice features that the default .net json serializer doesn't have, like Null value handling, you just need to create the JsonSerializerSettings
:
public static string Serialize(T obj)
{
string result = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
return result;
}
Another serious serializer issue in .net is the self referencing loop. In the case of a student that is enrolled in a course, its instance has a course property and a course has a collection of students that means a List<Student>
which will create a reference loop. You can handle this with JsonSerializerSettings
:
public static string Serialize(T obj)
{
string result = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
return result;
}
You can put various serializations option like this:
public static string Serialize(T obj)
{
string result = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
return result;
}