So I have a JSON file that has an object nested within it. It looks like this:
{ "MyObject" : { "prop1": "Value1", "prop2" : "Value2"}
"Message" : "A message"}
Sometimes, the object nested inside the JSON may be null. So for example,
{ "MyObject" : null
"Message" : "A message"}
I'm trying to deserialize this object using Newtonsoft.Json into a type T of JsonObject
which has two properties:
MyObject
andMessage
.
JsonObject looks like this:
public class JsonObject
{
public MyObject MyObject { get; set; }
public string Message { get; set; }
}
Message is just a string, but MyObject is an object which has a few other (private) properties as well as a constructor:
public class MyObject
{
public MyObject(string prop1, string prop2)
{
this.prop1= prop1;
this.prop2= prop2;
}
public string prop1 { get; private set; }
public string prop2 { get; private set; }
}
My code to deserialize looks like this:
using (StreamReader reader = new StreamReader(filename))
{
string jsonFile = reader.ReadToEnd();
return JsonConvert.DeserializeObject<JsonObject>(jsonFile);
}
But it is throwing an error:
Exception: Object reference not set to an instance of an object
This happens when the MyObject object is null. I printed jsonFile, and this is the output:
{"MyObject": null, "Message": "sample message"}
What I want is for MyObject to deserialize to null. So when the code runs, the end result is a JsonObject
with
MyObject = null
andMessage = "sample message"
.
How do I do this using Newtonsoft.Json?