Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Lets say you have the following Json</p> <pre><code>string yourJsonString = "{\"FIRST_NAME\":\"Foo\",\"LAST_NAME\":\"Bar\"}"; </code></pre> <p>You could model this Json as:</p> <pre><code>public class JsonModel { [JsonProperty("FIRST_NAME")] public string FirstName {get; set;} [JsonProperty("LAST_NAME")] public string LastName {get; set;} } </code></pre> <p>Note that you can use <code>JsonPropertyAttribute</code> to tell <code>Json.Net</code> what the property's corresponding json field is.</p> <p>Now, that you have your model set up, can use <code>JsonConvert.DeserializeObject&lt;T&gt;(...)</code> to get a strongly typed instance of your json model.</p> <pre><code>JsonModel jsonModel = JsonConvert.DeserializeObject&lt;JsonModel&gt;(yourJsonString); string firstName = jsonModel.FirstName; // Foo string lastName = jsonModel.LastName; // Bar </code></pre> <p>As someone had mentioned, if you do it this way, you won't have to deal with <code>JObject</code> and moreover, it will force you to actually understand the structure of the json being returned.</p> <p>Specifically in your example, you could store an object of type <code>JsonModel</code> and in your model's constructor initialize it using <code>JsonConvert.DeserializeObject&lt;T&gt;</code>. Your public properties could then just call into that <code>JsonModel</code> instance and get the appropriate values. </p> <p>Here's a more detailed example. Assume you are getting back the json I had provided above and are using the same model we created before. Let's say you have a private field in your class of type <code>JsonModel</code></p> <pre><code>private JsonModel jsonModel; </code></pre> <p>You can initialize it in your constructor:</p> <pre><code>public UserModel() { WebClient request = new WebClient(); string response = request.DownloadString(url); jsonModel = JsonConvert.DeserializeObject&lt;JsonModel&gt;(response); } </code></pre> <p>Now, your public properties can simply call into this <code>JsonModel</code> object.</p> <pre><code>public string FirstName { get { return jsonModel.FirstName; } set { jsonModel.FirstName = value; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload