Newtonsoft.json将值333转换为类型时出错

时间:2014-10-28 20:25:26

标签: c# json.net

Newtonsoft.json似乎无法将int转换为我的nInt结构。我不确定为什么。我的struct的目的是允许int设置为null,但实际上不是null,而是默认为0。

这是我的代码:

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'.

1 个答案:

答案 0 :(得分:4)

您无需创建自己的类型即可。您可以使用JSON.NET中的NullValueHandling选项忽略null的非可空类型。例如:

public class TotalCountObject
{
    [JsonProperty(NullValueHandling = NullValueHanding.Ignore)]
    public int totalCount { get; set; }
}

由于int的默认值为0,因此忽略此属性时,其值将为零。

您还可以在JsonSerializerSettings中设置此属性:

var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;

TotalCountObject tco = JsonConvert.DeserializeObject<TotalCountObject>(
    jsonString, jsonSerializerSettings);

如果您不希望NullValueHandling应用于所有属性,那么这可能不是您想要的路线。