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.
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.
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.
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.
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);
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With