HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Newtonsoft Json helper class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
newtonsoftclassjsonhelper

Problem

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 contract, string filePath)
{
using (var fs = File.Open(filePath, FileMode.OpenOrCreate))
{
SerializeToStream(contract, fs);
}
}

public static void SaveContractToJSON(T contract, MemoryStream stream)
{
SerializeToStream(contract, stream);
}

private static void SerializeToStream(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(string filePath)
{
try
{
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
return DeserializeFromStream(fileStream);
}
}
catch (Exception)
{
return default(T);
}
}

public static T LoadContractFromJSON(MemoryStream stream)
{
try
{
return DeserializeFromStream(stream);
}
catch (Exception)
{
return default(T);
}
}

private static T DeserializeFromStream(Stream stream)
{
var serializer = new JsonSerializer();

using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
return serializer.Deserialize(jsonTextReader);

Solution

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?

Context

StackExchange Code Review Q#121877, answer score: 3

Revisions (0)

No revisions yet.