我无法将 json 中的带逗号的数字反序列化为 int。它抛出这个异常:
Newtonsoft.Json.JsonReaderException:'无法将字符串转换为整数:24,992。路径“请求”,第 1 行
这是我的代码:
public class PriceModel
{
public DateTime Date { get; set; }
public int Requests { get; set; }
public decimal Price { get; set; }
}
string json = "{\"Date\":\"2018-03-23\",\"Requests\":\"24,992\",\"Price\":\"95.96\"}";
PriceModel value = JsonConvert.DeserializeObject<PriceModel>(json, new JsonSerializerSettings
{
Culture = new CultureInfo("en-US")
});
Run Code Online (Sandbox Code Playgroud)
我希望“请求”属性的值为 24992。
有没有办法解决这个问题?
谢谢
好的,经过一些研究提出了以下解决方案,您无需更改任何类型或任何内容,并且可以根据您的要求工作。
反序列化时不要使用返回类型,var而是使用PriceModel,然后其他东西将保持不变。
创建ProcessChildModel继承ProcessModel并覆盖Requests属性的新类。
public class PriceModel
{
public DateTime Date { get; set; }
public int Requests { get; set; }
public decimal Price { get; set; }
}
public class PriceModelChild : PriceModel
{
public new string Requests
{
set
{
int num;
if (int.TryParse(value, NumberStyles.AllowThousands,
CultureInfo.InvariantCulture, out num))
{
base.Requests = num;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用新的子模型反序列化数据
string json = "{\"Date\":\"2018-03-23\",\"Requests\":\"24,992\",\"Price\":\"95.96\"}";
PriceModel value = JsonConvert.DeserializeObject<PriceModelChild>(json);
Run Code Online (Sandbox Code Playgroud)