JsonConvert.DeserializeObject: Deserialize JSON to C# POCO class
When dealing with RESTful APIs, it is often necessary to deserialize JSON responses into C# Plain Old CLR Objects (POCO). A commonly used method is JsonConvert.DeserializeObject.
Question:
Consider the following User POCO class:
User.cs:
<code class="language-c#">public class User { public string Username { get; set; } public string Name { get; set; } public string Location { get; set; } // ... [JsonProperty("accounts")] public List<Account> Accounts { get; set; } }</code>
When trying to deserialize JSON to this class using JsonConvert.DeserializeObject, an exception is thrown indicating that the JSON array cannot be deserialized into a list of Accounts.
Solution:
To solve this problem, there are two key points to consider:
1. Declare the Accounts property as an object:
Change the Accounts property declaration to represent an object instead of a list.
User.cs (updated):
<code class="language-c#">public class User { // ... [JsonProperty("accounts")] public Account Accounts { get; set; } }</code>
2. Use JsonProperty attribute:
Apply the JsonProperty attribute to each property to map JSON property names to C# property names.
User.cs (using JsonProperty):
<code class="language-c#">public class User { [JsonProperty("username")] public string Username { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("location")] public string Location { get; set; } // ... [JsonProperty("accounts")] public Account Accounts { get; set; } }</code>
Additional classes (Account and Badge):
Define additional classes for any nested objects such as Accounts and Badges, and apply JsonProperty properties accordingly.
Account.cs:
<code class="language-c#">public class Account { [JsonProperty("github")] public string Github { get; set; } }</code>
Badge.cs:
<code class="language-c#">public class Badge { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("description")] public string Description { get; set; } // ... }</code>
Example usage:
<code class="language-c#">using Newtonsoft.Json; using System.Net; class Program { static User LoadUserFromJson(string response) { var user = JsonConvert.DeserializeObject<User>(response); return user; } static void Main() { using (WebClient wc = new WebClient()) { var json = wc.DownloadString("http://coderwall.com/mdeiters.json"); var user = LoadUserFromJson(json); } } }</code>
With these changes, JsonConvert.DeserializeObject now successfully deserializes JSON to the User POCO class and handles nested objects (Accounts) appropriately.
The above is the detailed content of How to Resolve JsonConvert.DeserializeObject Errors When Deserializing JSON into C# POCO Classes?. For more information, please follow other related articles on the PHP Chinese website!