I've written the following helper class to help serializing objects to and from Json.
I would appreciate some feed back on the style of the class.
using System;
using System.IO;
using Newtonsoft.Json;
namespace Helpers
{
public static class Json
{
public static void SaveContractToJSON<T>(T contract, string filePath)
{
using (var fs = File.Open(filePath, FileMode.OpenOrCreate))
{
SerializeToStream(contract, fs);
}
}
public static void SaveContractToJSON<T>(T contract, MemoryStream stream)
{
SerializeToStream(contract, stream);
}
private static void SerializeToStream<T>(T contract, Stream stream)
{
var serializer = new JsonSerializer();
using (var sw = new StreamWriter(stream))
using (var writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, contract);
}
}
public static T LoadContractFromJSON<T>(string filePath)
{
try
{
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
return DeserializeFromStream<T>(fileStream);
}
}
catch (Exception)
{
return default(T);
}
}
public static T LoadContractFromJSON<T>(MemoryStream stream)
{
try
{
return DeserializeFromStream<T>(stream);
}
catch (Exception)
{
return default(T);
}
}
private static T DeserializeFromStream<T>(Stream stream)
{
var serializer = new JsonSerializer();
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
return serializer.Deserialize<T>(jsonTextReader);
}
}
}
}
1 Answer 1
Your class name is Json
yet your methods contain this acronym in all-uppercase: JSON
. The naming conventions say: "Do capitalize only the first character of acronyms with three or more characters, except the first word of a camel-cased identifier."
fs
isn't a clear variable name. Same for sw
(why not use streamWriter
?) and sr
(streamReader
). I'd even include writer
.
Considering that you don't use var serializer = new JsonSerializer();
until later, why not delay this call until you need it?
I'm bothered by catch (Exception)
. Are you certain you don't want to know that something went wrong, and what exactly went wrong?