Utility Class – JSON to C# Object

The idea is that I can call this utility class specifying the type of class I want and the path to the JSON file.

The utility should cache the results, with a cache dependency on the file.

Here’s the c# code

public static class JSONUtils
        public static T Load<T>(string path)
            if (!File.Exists(path))
                return default(T);

            string cacheKey = string.Format("JSON_{0}", path);
            MemoryCache memoryCache = MemoryCache.Default;
            CacheItemPolicy cachePolicy = new CacheItemPolicy();

            if (memoryCache[cacheKey] == null)

                using (StreamReader r = new StreamReader(path))
                    string json = r.ReadToEnd();

                    var items = JsonSerializer.DeserializeFromString<T>(json);

                    List<string> FileDependencies = new List<string> {path};

                    cachePolicy.ChangeMonitors.Add(new HostFileChangeMonitor(FileDependencies));
                    memoryCache.Add(cacheKey, items, cachePolicy);

            return (T)memoryCache[cacheKey];


Example JSON

"Name": "Product 1",
"ID": 4710323,
"Price": 15.00
"Name": "Product 2",
"ID": 4710325,
"Price": 39.00

A class to match the JSON

public class Product
        public string Name { get; set; }
        public int ID { get; set; }
        public decimal Price { get; set; }

How to use

var products = 

1 thought on “Utility Class – JSON to C# Object

  • This is using servicestack to deserialize. If you’re using JSON.net then use
    var items = JsonConvert.DeserializeObject(json);

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.