Reputation: 5375
Newtonsoft.json does not seem to be able to convert int to my nInt struct. I'm not sure why. The purpose of my struct is to allow int to be set to null, but not actually be null and instead default to 0.
Here is my code:
nInt:
/// <summary>
/// Non-nullable int. Defaults to 0.
/// </summary>
public struct nInt
{
public nInt(int? value)
: this()
{
Value = value ?? 0;
}
private void deNullify()
{
Value = Value ?? 0;
}
public int? Value
{
get;
private set;
}
public static implicit operator nInt(int value)
{
return new nInt(value);
}
public static implicit operator nInt(int? value)
{
return new nInt(value);
}
public static implicit operator int?(nInt value)
{
return value.Value ?? 0;
}
public static implicit operator int(nInt value)
{
return value.Value ?? 0;
}
public override bool Equals(object other)
{
deNullify();
return Value.Equals(other);
}
public override int GetHashCode()
{
deNullify();
return Value.GetHashCode();
}
public Type GetType()
{
return typeof(int?);
}
public int GetValueOrDefault(int defaultValue)
{
deNullify();
return Value.GetValueOrDefault(defaultValue);
}
public bool HasValue
{
get { deNullify(); return Value.HasValue; }
}
public override string ToString()
{
deNullify();
return Value.ToString();
}
}
nInt usage:
public class TotalCountObject
{
public nInt totalCount { get; set; }
}
TotalCountObject tco = JsonConvert.DeserializeObject<TotalCountObject>(jsonString, jsonSerializerSettings);
// here is where i get Error converting value 333 to type 'nInt'.
Upvotes: 0
Views: 759
Reputation: 126042
You don't need to create your own type to do this. You can use the NullValueHandling
options in JSON.NET to ignore null
s for non-nullable types. For example:
public class TotalCountObject
{
[JsonProperty(NullValueHandling = NullValueHanding.Ignore)]
public int totalCount { get; set; }
}
Since the default value of int
is 0
, when this property is ignored, its value will be zero.
You can also set this property in JsonSerializerSettings
:
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
TotalCountObject tco = JsonConvert.DeserializeObject<TotalCountObject>(
jsonString, jsonSerializerSettings);
Although that may not be a route you want to take if you don't want the NullValueHandling
to apply to all properties.
Upvotes: 4