Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize Json using ToObject method results in default properties values

I am trying to create a .NET Object from a JObject but I am getting all properties of the Object as defaults (null for string , 0 for int etc.)

I am creating a simple Jobject:

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

The car class is:

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

The deserialization is here:

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

But the result in run time is default values: Run time picture

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

Thanks

like image 958
Aviran Barda Avatar asked May 01 '16 14:05

Aviran Barda


1 Answers

You have not defined an access modifier to your properties. Without explicitly setting the access modifier (e.g: public protected internal private) a property will be private.

Newtonsoft.Json requires a public setter in order 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 having your setters public isn't an option for your. Consider the other options listed in this SO answer.

like image 198
Bruno Garcia Avatar answered Oct 24 '22 04:10

Bruno Garcia