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];
        }
    }

Usage

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 = 
    JSONUtils.Load<List<Product>>(Server.MapPath("~/App_Data/products.json"));

Leave a Reply

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