0

How to default-ly instantiate null values while deserializing with RestSharp.

For example you have this POCO

public class Address {
    public string Street { get; set; }
    public string City { get; set; }
    public int Number { get; set; }
    public string Postal { get; set; }
}

public class Root {
    public string Name { get; set; }
    public Address Address { get; set; }
}

And this JSON:

{ 
    "Root": {
        "Name" : "John",
        "Address" : null 
    }
}

Is it possible when I do RestClient.ExecuteAsGet<Root>( ... ), that even though the Address is null, it still gets instantiated (new Address())?

Highmastdon
  • 6,511
  • 7
  • 37
  • 64
  • 1
    not familiar with RestSharp, but can't you just add a default constructor to Root that news up Address? – Crowcoder Jan 13 '15 at 20:30
  • 1
    I would say you shouldn't do that. If you initialize an empty Address object, it would also initialize any value-type fields in it. In your case, Address.Number would have a default value of 0. Any such defaults are better left to the default constructor. – sudheeshix Jan 13 '15 at 20:30
  • @Crowcoder yea that might be a good idea (see also next comment) – Highmastdon Jan 13 '15 at 20:42
  • @sudheeshix yes I know, but I'm directly storing it in the database and a limitation of Entity Framework is that it cannot store 'complex types' as null values. It needs to create a record. Which is quite annoying, but I thought maybe it can be resolved in RestSharp, so I dont have to bother furtheron in the code. – Highmastdon Jan 13 '15 at 20:44
  • As this is more related to Entity Framework, have you reviewed these 2 questions for possible ideas? [Exclude Property on Update in Entity Framework](http://stackoverflow.com/questions/12661881) and [Update an entity using entity framework while ignoring some properties](http://stackoverflow.com/questions/25734567) – Metro Smurf Jan 08 '16 at 15:06

1 Answers1

-1

This may have changed in newer versions of RestSharp, but objects should be null by default if they are not present or null.

You can accomplish this with value types by using Nullable. https://msdn.microsoft.com/en-us/library/b3h38hb0.aspx

public class Root {
    public Nullable<DateTime> date { get; set; }
}
tribone
  • 1
  • 1
  • This is absolutely wrong, re: `Nullable` is for value types and `Address` is a reference type. Even from the link you provided: "A type is said to be nullable if it can be assigned a value or can be assigned null, which means the type has no value whatsoever. By default, all reference types, such as String, are nullable, but all value types, such as Int32, are not." – Metro Smurf Jan 08 '16 at 00:18