Skip to content

Instantly share code, notes, and snippets.

@rabryst
Created August 3, 2017 03:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rabryst/22b1750809738a7e9ec17d72d4927cc4 to your computer and use it in GitHub Desktop.
Save rabryst/22b1750809738a7e9ec17d72d4927cc4 to your computer and use it in GitHub Desktop.
Wrapper for reading and writing classes to and from disk (using Newtonsoft.Json.dll)
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
namespace JsonPersistenceExample
{
public static class JsonWrangler
{
public static void WriteJsonItem<T>(T item, FileInfo outputFile)
{
var serialiser = new JsonSerializer();
using (var sw = new StreamWriter(outputFile.FullName))
{
using (var writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
serialiser.Serialize(writer, item);
}
}
}
public static void WriteJsonList<T>(List<T> listOfObjects, FileInfo outputFile)
{
var serialiser = new JsonSerializer();
using (var sw = new StreamWriter(outputFile.FullName))
{
using (var writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
serialiser.Serialize(writer, listOfObjects);
}
}
}
public static T ReadJsonItem<T>(FileInfo file)
{
var deserialiser = new JsonSerializer();
var reader = new JsonTextReader(new StreamReader(file.FullName));
return deserialiser.Deserialize<T>(reader);
}
public static List<T> ReadJson<T>(FileInfo file)
{
var deserialiser = new JsonSerializer();
var reader = new JsonTextReader(new StreamReader(file.FullName));
return deserialiser.Deserialize<List<T>>(reader);
}
}
}
@rabryst
Copy link
Author

rabryst commented Aug 3, 2017

If you need to persist classes to disk, and read them again later (in configuration files for example), use the above code in a class, and call it like so:

Write to the config file:

var config = new ConfigurationEntity() { Value1 = "val1", Value2 = "val2" };
JsonWrangler.WriteJsonItem(config, new FileInfo("config.json"));

Read from the config file:

var config = JsonWrangler.ReadJsonItem<ConfigurationEntity>(new FileInfo("config.json"));

Lists and more ...

Write a generic List<T>:

var entityList = new List<T>() { new T { Value1 = "val1", Value2 = "val2" }, new T { Value1 = "val3", Value2 = "val4" } };
JsonWrangler.WriteJsonList(entityList, new FileInfo("list.json"));

Read the generic List<T> back again:

var entityList = JsonWrangler.ReadJson<T>(new FileInfo("list.json"));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment