snipt

Ctrl+h for KB shortcuts

C#

JSON.NET: Deserialize to an object

1
2
3
4
5
6
7
8
// Taken from a blogpost on Scott Hanselman's blog.. we grab some JSON,
// and using the JSON.NET JObject, we can parse the response/JSON to a dynamic object 'o'

var client = new WebClient();
client.Headers.Add("User-Agent", "Nobody");
var response = client.DownloadString(new Uri("http://www.hanselman.com/smallestdotnet/json.ashx"));
JObject o = JObject.Parse(response);'
//Now o is an object I can walk around...
https://snipt.net/embed/5979a8fac8ef45989adffe927b4ebb4f/
/raw/5979a8fac8ef45989adffe927b4ebb4f/
5979a8fac8ef45989adffe927b4ebb4f
csharp
C#
8
2019-07-21T19:24:28
True
False
False
/api/public/snipt/41569/
jsonnet-deserialize-to-an-object
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#L-1">1</a> <a href="#L-2">2</a> <a href="#L-3">3</a> <a href="#L-4">4</a> <a href="#L-5">5</a> <a href="#L-6">6</a> <a href="#L-7">7</a> <a href="#L-8">8</a></pre></div></td><td class="code"><div class="highlight"><pre><span></span><span id="L-1"><a name="L-1"></a><span class="c1">// Taken from a blogpost on Scott Hanselman&#39;s blog.. we grab some JSON,</span> </span><span id="L-2"><a name="L-2"></a><span class="c1">// and using the JSON.NET JObject, we can parse the response/JSON to a dynamic object &#39;o&#39;</span> </span><span id="L-3"><a name="L-3"></a> </span><span id="L-4"><a name="L-4"></a><span class="kt">var</span> <span class="n">client</span> <span class="p">=</span> <span class="k">new</span> <span class="n">WebClient</span><span class="p">();</span> </span><span id="L-5"><a name="L-5"></a><span class="n">client</span><span class="p">.</span><span class="n">Headers</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="s">&quot;User-Agent&quot;</span><span class="p">,</span> <span class="s">&quot;Nobody&quot;</span><span class="p">);</span> </span><span id="L-6"><a name="L-6"></a><span class="kt">var</span> <span class="n">response</span> <span class="p">=</span> <span class="n">client</span><span class="p">.</span><span class="n">DownloadString</span><span class="p">(</span><span class="k">new</span> <span class="n">Uri</span><span class="p">(</span><span class="s">&quot;http://www.hanselman.com/smallestdotnet/json.ashx&quot;</span><span class="p">));</span> </span><span id="L-7"><a name="L-7"></a><span class="n">JObject</span> <span class="n">o</span> <span class="p">=</span> <span class="n">JObject</span><span class="p">.</span><span class="n">Parse</span><span class="p">(</span><span class="n">response</span><span class="p">);</span><span class="err">&#39;</span> </span><span id="L-8"><a name="L-8"></a><span class="c1">//Now o is an object I can walk around...</span> </span></pre></div> </td></tr></table>
c#, deserialize, json, json.net