Deserialize Json Using ToObject Method Returns Default Values

I am trying to create a .NET object from JObject, but I get all the properties of the object as default values ​​(null for string, 0 for int, etc.)

I create a simple Jobject:

var jsonObject = new JObject(); jsonObject.Add("type", "Fiat"); jsonObject.Add("model", 500); jsonObject.Add("color", "white"); 

Car class:

 public class Car { string type {get;set;} int model {get ;set;} string color {get;set;} } 

deserialization here:

 Car myCar = jsonObject.ToObject<Car>(); 

But the result at runtime is the default values: Runtime Image

I would like to know why this is happening and how I should do it right,

thanks

+5
source share
1 answer

You have not defined an access modifier for your properties. Without explicit configuration of the access modifier (for example: public protected internal private ), the property will be closed.

Newtonsoft.Json requires a public setter to set the value of your property.

Try:

 public class Car { public string type { get; set; } public int model { get; set; } public string color { get; set; } } 

If your public setters are not an option for you. Consider the other options listed in this SO answer .

+5
source

All Articles