Using JsonConvert.DeserializeObject to Deserialize Json to C # POCO Class

Here is my simple User POCO class:

 /// <summary> /// The User class represents a Coderwall User. /// </summary> public class User { /// <summary> /// A User username. eg: "sergiotapia, mrkibbles, matumbo" /// </summary> public string Username { get; set; } /// <summary> /// A User name. eg: "Sergio Tapia, John Cosack, Lucy McMillan" /// </summary> public string Name { get; set; } /// <summary> /// A User location. eh: "Bolivia, USA, France, Italy" /// </summary> public string Location { get; set; } public int Endorsements { get; set; } //Todo. public string Team { get; set; } //Todo. /// <summary> /// A collection of the User linked accounts. /// </summary> public List<Account> Accounts { get; set; } /// <summary> /// A collection of the User awarded badges. /// </summary> public List<Badge> Badges { get; set; } } 

And the method that I use to deserialize the JSON response into a User object (this actual JSON call is here ):

 private User LoadUserFromJson(string response) { var outObject = JsonConvert.DeserializeObject<User>(response); return outObject; } 

This throws an exception:

It is not possible to deserialize the current JSON object (for example, {"name": "value"}) to type 'System.Collections.Generic.List`1 [CoderwallDotNet.Api.Models.Account] because it requires a JSON array (for example, [ 1,2,3]) for deserialization correctly.

To fix this error, either change the JSON to a JSON array (for example, [1,2,3]) or change the deserialized type so that it is a normal .NET type (for example, not a primitive type of integer type, but not a set of type like an array or a list) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to a type to force it to deserialize from a JSON object. Accounts.github path, line 1, position 129.

I've never worked with this DeserializeObject method before, I'm kinda stuck here.

I made sure that the property names in the POCO class match the names in the JSON response.

What can I try to deserialize JSON in this POCO class?

+39
json c # serialization poco
Jun 20 '12 at 18:52
source share
7 answers

Here is a working example.

Key points:

  • Ad Accounts
  • Using the JsonProperty

.

 using (WebClient wc = new WebClient()) { var json = wc.DownloadString("http://coderwall.com/mdeiters.json"); var user = JsonConvert.DeserializeObject<User>(json); } 

-

 public class User { /// <summary> /// A User username. eg: "sergiotapia, mrkibbles, matumbo" /// </summary> [JsonProperty("username")] public string Username { get; set; } /// <summary> /// A User name. eg: "Sergio Tapia, John Cosack, Lucy McMillan" /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// A User location. eh: "Bolivia, USA, France, Italy" /// </summary> [JsonProperty("location")] public string Location { get; set; } [JsonProperty("endorsements")] public int Endorsements { get; set; } //Todo. [JsonProperty("team")] public string Team { get; set; } //Todo. /// <summary> /// A collection of the User linked accounts. /// </summary> [JsonProperty("accounts")] public Account Accounts { get; set; } /// <summary> /// A collection of the User awarded badges. /// </summary> [JsonProperty("badges")] public List<Badge> Badges { get; set; } } public class Account { public string github; } public class Badge { [JsonProperty("name")] public string Name; [JsonProperty("description")] public string Description; [JsonProperty("created")] public string Created; [JsonProperty("badge")] public string BadgeUrl; } 
+65
Jun 20 '12 at 20:12
source share

You can create a JsonConverter . See here for an example similar to your question.

+4
Jun 20 2018-12-12T00:
source share

Another and more streamlined approach to deserializing a camel wrapped JSON string into a pascal POCO object is to use CamelCasePropertyNamesContractResolver .

This is part of the Newtonsoft.Json.Serialization namespace. This approach assumes that the only difference between a JSON object and a POCO is in the shell of the property names. If property names are spelled differently, you need to resort to using JsonProperty attributes to display property names.

 using Newtonsoft.Json; using Newtonsoft.Json.Serialization; . . . private User LoadUserFromJson(string response) { JsonSerializerSettings serSettings = new JsonSerializerSettings(); serSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); User outObject = JsonConvert.DeserializeObject<User>(jsonValue, serSettings); return outObject; } 
+4
Dec 19 '14 at 22:05
source share

The property of accounts is defined as follows:

 "accounts":{"github":"sergiotapia"} 

POCO states the following:

 public List<Account> Accounts { get; set; } 

Try using this Json:

 "accounts":[{"github":"sergiotapia"}] 

An array of elements (which will be displayed in the list) is always enclosed in square brackets.

Edit: The Poco account will look something like this:

 class Account { public string github { get; set; } } 

and possibly other properties.

Edit 2: To not have an array, use the property as follows:

 public Account Accounts { get; set; } 

with something like the sample class that I posted in the first edit.

+2
Jun 20 '12 at 18:59
source share
 to fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object.` 

The entire message indicates that it is possible to serialize the List object, but the input should be a JSON list. That means your JSON should contain

 "accounts" : [{<AccountObjectData}, {<AccountObjectData>}...], 

Where AccountObject data is a JSON representing your account object or icon object

Currently it looks like

 "accounts":{"github":"sergiotapia"} 

If the accounts are a JSON object (indicated by a curly brace) and not an array of JSON objects (arrays are indicated by brackets), this is what you want. Try

 "accounts" : [{"github":"sergiotapia"}] 
+2
Jun 20 2018-12-06T00:
source share

This is not exactly what I had in mind. What do you do if you have a generic type that will only be known at run time?

 public MyDTO toObject() { try { var methodInfo = MethodBase.GetCurrentMethod(); if (methodInfo.DeclaringType != null) { var fullName = methodInfo.DeclaringType.FullName + "." + this.dtoName; Type type = Type.GetType(fullName); if (type != null) { var obj = JsonConvert.DeserializeObject(payload); //var obj = JsonConvert.DeserializeObject<type.MemberType.GetType()>(payload); // <--- type ????? ... } } // Example for java.. Convert this to C# return JSONUtil.fromJSON(payload, Class.forName(dtoName, false, getClass().getClassLoader())); } catch (Exception ex) { throw new ReflectInsightException(MethodBase.GetCurrentMethod().Name, ex); } } 
0
Feb 26 '15 at 18:30
source share

According to the accepted answer, if you have a sample JSON text, you can connect it to this converter , select your parameters and generate C # code.

If you don't know the type at runtime, this question looks as if it fits.

dynamically deserialize json to any passed object. FROM#

0
Feb 27 '17 at 23:24
source share



All Articles