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?

5
  • Are you using Json.net to deserialize the json? Commented Jan 14, 2017 at 7:09
  • @BrandonMinnick - yes, am using json.net Commented Jan 14, 2017 at 7: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 : stackoverflow.com/questions/8254503/… Commented Jan 14, 2017 at 7:14
  • 1
    does that even compile? your type hierarchy doesn't conform to the specified json. Commented Jan 14, 2017 at 7: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! Commented Jan 17, 2017 at 4:01

1 Answer 1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.