Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize json into C# object for class which has default private constructor

Tags:

I need to deserialize json for following class.

public class Test {     public string Property { get; set; }      private Test()     {         //NOTHING TO INITIALIZE     }      public Test(string prop)     {         Property = prop;     } } 

I can create an instance of Test like

var instance = new Test("Instance"); 

considering my json something like

"{  "Property":"Instance" }" 

How shall I create an object of Test class as my default constructor is private and I am getting object where Property is NULL

I am using Newtonsoft Json parser.

like image 219
Shantanu Gupta Avatar asked Jun 16 '14 12:06

Shantanu Gupta


People also ask

How do I deserialize JSON data?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

Can C parse JSON?

jsmn (pronounced like 'jasmine') is a minimalistic JSON parser in C. It can be easily integrated into the resource-limited projects or embedded systems. You can find more information about JSON format at json.org.

How does JSON deserialize work?

In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it creates a JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns a custom object (BlogSites) from JSON data.


2 Answers

You can make Json.Net call the private constructor by marking it with a [JsonConstructor] attribute:

[JsonConstructor] private Test() {     //NOTHING TO INITIALIZE } 

Note that the serializer will still use the public setters to populate the object after calling the constructor.


Another possible option is to use the ConstructorHandling setting:

JsonSerializerSettings settings = new JsonSerializerSettings {     ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor };  Test t = JsonConvert.DeserializeObject<Test>(json, settings); 
like image 175
Brian Rogers Avatar answered Oct 03 '22 22:10

Brian Rogers


It doesn't seem like you need to take any extra steps.

Using Json.NET v6.0.8, the following C# program works inside LINQPad:

void Main() {        var o = JsonConvert.DeserializeObject<Test>("{\"Property\":\"Instance\"}");      Debug.Assert(o.Property == "Instance",         "Property value not set when deserializing."); }  public class Test {     public string Property { get; set; }      private Test()     {     }      public Test(string propertyValue)     {         Property = propertyValue;     } } 
like image 43
Dave Watts Avatar answered Oct 03 '22 22:10

Dave Watts