1

I have a few classes that map to below structure/hierarchy.

public class CustomModel
{
     public string Message { get; set; }

     public int Code { get; set; }

     public CustomData Info { get; set; } 
}

public class CustomData 
{

    public CustomData (CustomObject customData)
    {
        CustomObjectProp = customData.customMessage
    }
}

public class CustomObject 
{
    public string CustomObjectProp {get; set;}
}

When serializing CustomModel I get a Json string like below

{
  "Message ": "A message is set.",
  "Code": 825,
  "Info": "Some Info is set"
}

However when deserializing I get an System.NullReferenceException error as the constructor of CustomData gets called with customData being null.

How can I avoid the 'getter' to execute before the setter?

gideon
  • 19,329
  • 11
  • 72
  • 113
Noah
  • 133
  • 7
  • Are you using [Json.net](https://www.nuget.org/packages/newtonsoft.json) to deserialize the json? – Brandon Minnick Jan 14 '17 at 07:09
  • @BrandonMinnick - yes, am using json.net – Noah Jan 14 '17 at 07:13
  • I would suggest adding a default constructor also and setting up some default data. Other than that you could look into writing a customer converter to handle the parameterized constructor : http://stackoverflow.com/questions/8254503/how-to-pass-arguments-to-a-non-default-constructor/8312048#8312048 – gideon Jan 14 '17 at 07:14
  • 1
    does that even compile? your type hierarchy doesn't conform to the specified json. – Amit Kumar Ghosh Jan 14 '17 at 07:14
  • Hi Noah! Let me know if my answer, below, helped solve your problem! If it did, let's mark it as Answered to help future developers who may have the same question! – Brandon Minnick Jan 17 '17 at 04:01

1 Answers1

0

To avoid the Null Reference Exception, perform a null check in the constructor.

public class CustomData 
{    
    public CustomData (CustomObject customData)
    {
        if(customData != null)
            CustomObjectProp = customData.customMessage
    }
}

If you are using C#6, you can take advantage of the Null Conditioner Operator to perform the null check in-line.

public class CustomData 
{
    public CustomData (CustomObject customData)
    {
        CustomObjectProp = customData?.customMessage
    }
}
Brandon Minnick
  • 13,342
  • 15
  • 65
  • 123