3
\$\begingroup\$

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);
 }
 }
 }
}
asked Mar 4, 2016 at 10:13
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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?

answered Mar 4, 2016 at 11:02
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.