5

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

Andrew Savinykh
  • 25,351
  • 17
  • 103
  • 158

1 Answers1

5

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.

Community
  • 1
  • 1
Bruno Garcia
  • 6,029
  • 3
  • 25
  • 38