Created
August 3, 2017 03:14
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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"));