Use JsonConvert.DeserializeObject to parse JSON to C# POCO class
When encountering errors (such as "Unable to deserialize..." exception) when deserializing JSON to a C# POCO class, it is crucial to understand the requirements for successful deserialization.
Specifically, the JsonConvert.DeserializeObject
method requires that the JSON conforms to the expected structure and data type defined in the POCO class.
Resolving errors
The key to solving this error lies in two aspects:
Correctly declare list properties:
Make sure the JSON response contains an array of objects for the properties declared as List<T>
in the POCO class. For example:
<code class="language-json"> { "username": "username", // ... 其他属性 "accounts": [ { "github": "github-username" }, // ... 其他帐户 ] }</code>
In a POCO class, the Accounts
attribute should be declared as:
<code class="language-csharp"> [JsonProperty("accounts")] public List<Account> Accounts { get; set; }</code>
Use JsonProperty attribute:
JsonProperty
attributes map JSON attribute names to corresponding POCO class attributes. By default, JSON property names are case-sensitive and match C# property names. To customize this mapping, use the JsonProperty
attribute:
<code class="language-csharp"> [JsonProperty("github")] public string GithubUsername { get; set; }</code>
Example
Here is a corrected example:
<code class="language-csharp">public class User { [JsonProperty("username")] public string Username { get; set; } // ... 其他属性 [JsonProperty("accounts")] public List<Account> Accounts { get; set; } } public class Account { [JsonProperty("github")] public string GithubUsername { get; set; } } // 反序列化代码 var json = @"{ 'username': 'jdoe', // ... 其他属性 'accounts': [{ 'github': 'jdoe-github' }] }"; var user = JsonConvert.DeserializeObject<User>(json);</code>
The above is the detailed content of How to Successfully Deserialize JSON into a C# POCO Class Using JsonConvert.DeserializeObject?. For more information, please follow other related articles on the PHP Chinese website!