将字符串转换为数字分组符号的整数

本文关键字:符号 整数 数字 字符串 转换 | 更新日期: 2023-09-27 18:19:09

我得到一个错误,即'无法将字符串转换为整数:3.500。路径'Quantity " 当json转换为object.

json:
{"ProductCalcKey":"xxx","PaperType":"1","Quantity":"3.500"}
对象:

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; }
}

我正在使用下面的方法。

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());
}

如何在不触及jsontext的情况下解决这个问题?

将字符串转换为数字分组符号的整数

我用这种方法解决了这个问题。

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);
}