0
Newtonsoft.json似乎無法將int轉換爲我的nInt結構。我不知道爲什麼。我的結構的目的是允許INT設置爲空,但實際上沒有爲null,而是默認爲0。Newtonsoft.json將333錯誤轉換爲類型
這裏是我的代碼:
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使用:
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'.
我會咬 - 可空已經定義了一個GetValueOrDefault()方法。 –
48klocs
2014-10-28 20:39:07