JSONCONVERT STRING TO INTEGER ABOUT DIGIT GROUPING SYMBOL

Dag Hammarskjold

Total Post:24

Points:168
Posted by  Dag Hammarskjold
JSON 
 1505  View(s)
Ratings:
Rate this:
Hi Guys,

I get an error that is 'Could not convert string to integer: 3.500. Path 'Quantity'' while json converting to object.

json :

{"ProductCalcKey":"xxx","PaperType":"1","Quantity":"3.500"}
object:

public class UnitPrice
{
    public int UnitPriceId { get; set; }
    public int QuantityMin { get; set; }
    public int QuantityMax { get; set; }
    public decimal Price { get; set; }
    public string ProductCalcKey { get; set; }
    public PaperType? PaperType { get; set; }
    public int Quantity { get; set; }
}
I am using the following method.

protected object FromJsonToObject(Type t)
{
    Context.Request.InputStream.Position = 0;
    string json;
    using (var reader = new StreamReader(Context.Request.InputStream))
    {
        json = reader.ReadToEnd();
    }

    // todo: string to integer such as '222.222.222'
    return JsonConvert.DeserializeObject(json, t, new IsoDateTimeConverter());
}

How can I solve this problem without touching jsontext ?
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: JsonConvert string to integer about digit grouping symbol

    Hi,

    I have solved the problem in this way.

    public class FormatConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (objectType == typeof(int))
            {
                return Convert.ToInt32(reader.Value.ToString().Replace(".", string.Empty));
            }

            return reader.Value;
        }

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


    [Test]
    public void ConvertJson()
    {
        const string Json = "{\"ProductCalcKey\":\"xxx\",\"PaperType\":\"1\",\"Quantity\":\"3.500\"}";
        var o = (UnitPrice)JsonConvert.DeserializeObject(Json, typeof(UnitPrice), new FormatConverter());
        Assert.AreEqual(3500, o.Quantity);
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!