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

<br />
public static class JSONUtils<br />
    {<br />
        public static T Load&lt;T&gt;(string path)<br />
        {<br />
            if (!File.Exists(path))<br />
                return default(T);</p>
<p>            string cacheKey = string.Format(&quot;JSON_{0}&quot;, path);<br />
            MemoryCache memoryCache = MemoryCache.Default;<br />
            CacheItemPolicy cachePolicy = new CacheItemPolicy();</p>
<p>            if (memoryCache[cacheKey] == null)<br />
            {</p>
<p>                using (StreamReader r = new StreamReader(path))<br />
                {<br />
                    string json = r.ReadToEnd();</p>
<p>                    var items = JsonSerializer.DeserializeFromString&lt;T&gt;(json);</p>
<p>                    List&lt;string&gt; FileDependencies = new List&lt;string&gt; {path};</p>
<p>                    cachePolicy.ChangeMonitors.Add(new HostFileChangeMonitor(FileDependencies));<br />
                    memoryCache.Add(cacheKey, items, cachePolicy);<br />
                }<br />
            }</p>
<p>            return (T)memoryCache[cacheKey];<br />
        }<br />
    }<br />

Usage

Example JSON

<br />
[{<br />
&quot;Name&quot;: &quot;Product 1&quot;,<br />
&quot;ID&quot;: 4710323,<br />
&quot;Price&quot;: 15.00<br />
},<br />
{<br />
&quot;Name&quot;: &quot;Product 2&quot;,<br />
&quot;ID&quot;: 4710325,<br />
&quot;Price&quot;: 39.00<br />
}]<br />

A class to match the JSON

<br />
public class Product<br />
    {<br />
        public string Name { get; set; }<br />
        public int ID { get; set; }<br />
        public decimal Price { get; set; }<br />
    }<br />

How to use

<br />
var products =<br />
    JSONUtils.Load&lt;List&lt;Product&gt;&gt;(Server.MapPath(&quot;~/App_Data/products.json&quot;));<br />

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);
    instead

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.