GilliVilla
GilliVilla

Reputation: 5090

JSON empty string to null

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.

Upvotes: 1

Views: 361

Answers (3)

Krunal Mevada
Krunal Mevada

Reputation: 1655

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;

Upvotes: -1

victor
victor

Reputation: 1552

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.

Upvotes: 1

Steve
Steve

Reputation: 9603

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

public decimal? StreetValue { get; set; }

Upvotes: 3

Related Questions