Skip to main content
 首页 » 编程设计

c#之无法使用 Json.Net 反序列化指数数值

2024年02月06日11powertoolsteam

我正在解析来自股票交易市场的一些值,我的解析器工作正常,但在某些情况下,我连接到的 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); 
    } 
}