1

An empty string is usually parsed to null in JSON but I have a request which contains:

"StreetValue":"",

In my class it is de-serialized as a decimal

public decimal StreetValue { get; set; }

But when I pass the empty string it is getting de-serialized as 0.00M instead of null. What am I missing?

My intent is for it to be de-serialized as 0 only if "0.00M" is passed else it should be null.

1
  • 3
    decimal is not nullable, you cannot assign null to decimal. Commented Nov 10, 2015 at 4:23

3 Answers 3

3

Try marking your property as a nullable type (note the question mark):

public decimal? StreetValue { get; set; }
Sign up to request clarification or add additional context in comments.

Comments

1

That is because string is a reference type, whereas decimal is a value type, so it can't be assigned null; instead, your property will receive default(decimal).

As Steve said, you can make your property nullable:

decimal? Prop { get; set; }

This will allow you to use null as you wish.

Comments

-1

Try to make your property to dynamic so you no need to declare data type and not to worry about null value.

public dynamic StreetValue { get; set; }

Edit:

In c# 6.0 property initialization will be available:

public decimal StreetValue { get; set; } = 0.0;

3 Comments

This means you lose the type of the property so is not very useful.
@Steve Have you use before that ?
@GilliVilla if you not get value in this property as my answer you get null or empty string when you de-serialized

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.