当使用newtonsoft json.net反序列化字符串时,如何将空字符串转换为null为可空的int?

时间:2012-03-22 15:37:40

标签: c# nullable json.net

例如,如果我有

public class MyClass
{
    public Int32? Id { get;set; }
    public string Description { get;set; }
}

我的json字符串如下所示:

"{\"Id\":\"\",\"Description\":\"test\"}"

我收到错误“无法将字符串转换为整数”

1 个答案:

答案 0 :(得分:18)

像svick所说,你应该修改你的Json。但是,如果它是您无法控制的外部Json,那么您可以使用JsonConverter。

public class StringToNIntConverter : JsonConverter
{

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(int?);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        if (reader.TokenType == JsonToken.Integer)
            return reader.Value;

        if (reader.TokenType == JsonToken.String)
        {
            if (string.IsNullOrEmpty((string)reader.Value))
                return null;
            int num;
            if (int.TryParse((string)reader.Value, out num))
                return num;

            throw new JsonReaderException(string.Format("Expected integer, got {0}", reader.Value));
        }
        throw new JsonReaderException(string.Format("Unexcepted token {0}", reader.TokenType));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(value);
    }
}

public class MyClass
{
    [JsonConverter(typeof(StringToNIntConverter))]
    public Int32? Id { get; set; }
    public string Description { get; set; }
}