无法使用 Json.Net 反序列化指数数字



我正在解析证券交易所市场的一些值,我的解析器工作正常,除了在某些情况下,我连接到的API中的数值返回如下内容:

{
   "stock_name": "SOGDR50",
   "price": "6.1e-7"
}

在大多数请求中,price以十进制形式出现(例如:0.00757238),一切正常,但是当price是指数表示时,我的解析器会中断。

我正在使用Json.Net:http://www.newtonsoft.com/json

我的代码是:

T response = JsonConvert.DeserializeObject<T>(jsonResult);

我玩了JsonSerializerSettings但没有想出任何解决方案。我可以手动解析有问题的数字,但我需要响应自动反序列化为正确的对象,具体取决于调用的 API 方法。

关于如何解决这个问题的任何想法?

编辑 1:

public class StockResponse
{
    [JsonConstructor]
    public StockResponse(string stock_name, string price)
    {
        Stock_Name = stock_name;
        Price = Decimal.Parse(price.ToString(), NumberStyles.Float);
    }
    public String ShortName { get; set; }
    public String LongName { get; set; }
    public String Stock_Name{ get; set; }
    public Decimal Price { get; set; }
    public Decimal Spread { get; set; }
}

>JSON.NET包含可附加到自定义构造函数的[JsonConstructor]的属性。有了它,您可以这样做:

[JsonConstructor]
//The names of the parameters need to match those in jsonResult
public StockQuote(string stock_name, string price)
{
    this.stock_name = stock_name;
    //You need to explicitly tell the system it is a floating-point number
    this.price = Decimal.Parse(price, System.Globalization.NumberStyles.Float);
}

编辑:

除上述内容外,还使用 [JsonObject] 属性标记您的类。这是序列化和反序列化所必需的。我能够使用以下方法成功序列化和反序列化:

class Program
{
    static void Main(string[] args)
    {
        var quote = new StockQuote("test", "6.1e-7");
        string data = JsonConvert.SerializeObject(quote);
        Console.WriteLine(data);
        StockQuote quoteTwo = JsonConvert.DeserializeObject<StockQuote>(data);
        Console.ReadLine();
    }
}
[JsonObject]
public class StockQuote
{
    //If you want to serialize the class into a Json, you will need the
    //JsonProperty attributes set
    [JsonProperty(PropertyName="name")]
    public string Name { get; set; }
    [JsonProperty(PropertyName="price")]
    public decimal Price { get; set; }
    [JsonConstructor]
    public StockQuote(string name, string price)
    {
        this.Name = name;
        this.Price = Decimal.Parse(price, System.Globalization.NumberStyles.Float);
    }
}

最新更新