Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using newtonsoft json.net to deserialize a string, how do I convert an empty string to null for a nullable int?

For example, if I have

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

and my json string looks like this:

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

I get the error "Could not convert string to integer"

like image 484
user1286307 Avatar asked Mar 22 '12 15:03

user1286307


1 Answers

Like svick said, you should instead fix your Json. However if it is external Json which you have no control over then you can use 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; }
}
like image 56
Will Avatar answered Nov 15 '22 04:11

Will