0

I have two

public class CustomerInformation
{
public int? YearsofPurchase { get; set; }
public int? Age{ get; set; }
}

For some reason during deserialization to this object, when the json corresponding fields are null they are making the above two fields to show zero 0 instead of null.

Can someone point to tips please? Tried removing the two properties from Json when null so that during deserialization it would not have any value and then YearsofPurchase and Age would remain null.. but even then they are converting to 0.

 result = JsonConvert.DeserializeObject<CustomerInformation>(response, custDefualtSettings());

Values of my custDeafultsettings:

        TypeNameHandling = TypeNameHandling.All,
        TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full,
        MissingMemberHandling = MissingMemberHandling.Ignore,
        DefaultValueHandling = DefaultValueHandling.Include,                
        NullValueHandling = NullValueHandling.Include,

Actual Response:

                     {
                        "$id": "1",
                        "$type": "Customer.CustomerInformation, Customer.Common",
                        "CustomerId": 103606055,                                                   
                        "YearsofPurchase ": null,
                        "Age": null,
                        "PhoneNumber": "",
                        }

Tried removing the null properties from Json as shown below but still those properties value show as 0 on customerInformation.

                        {
                            "$id": "1",
                            "$type": "Customer.CustomerInformation, Customer.Common",
                            "CustomerId": 103606055,    
                            "PhoneNumber": "",
                            }
Ravio
  • 115
  • 9
  • Hi Dbc.... Sorry not making my JsonConvert.DeserializeObject code line embed in code braces did not show the actual object I was deserializing to. I have updated it. I also have added the response I am getting. – Ravio Nov 28 '20 at 05:20
  • Can't reproduce -- both `result.Age` and `result.YearsofPurchase` are deserialized as null. Proof: https://dotnetfiddle.net/MRYL40. Can you share a [mcve]? – dbc Nov 28 '20 at 06:09
  • Hi dbc .. this what I have control over the code.. The custDefualtSettings is actually used from a different DLL. for which I don't have access completely. WIll update after checking with the custDefualtSettings code author .. – Ravio Nov 29 '20 at 17:34
  • Then maybe there's some custom `JsonConverter` in `custDefualtSettings().Converters` (such as `NullToDefaultConverter` from [this answer](https://stackoverflow.com/a/31750851/3744182) to [Json.net deserialization null guid case](https://stackoverflow.com/q/31747712/3744182)) that is (de)serializing nullables as non-null default values. – dbc Nov 29 '20 at 19:14
  • Sure Dbc.. will check with them regarding it. Thank you – Ravio Nov 30 '20 at 04:40

0 Answers0