6

我正在尝试将 json 输出反序列化为 C# 对象。JSON结果:

{"order":{"commission":3.490000,"cost":4.490000,"duration":"day","extended_hours
":false,"fees":0.000000,"class":"equity","price":1.000000,"quantity":1.000000,"r
equest_date":"2013-11-26T09:43:17.118Z","result":true,"side":"buy","status":"ok"
,"symbol":"DIS","type":"limit"}}

我从 JSON 派生的类:

    public class Rootobject
{
    public Order Order { get; set; }
}

public class Order
{
    public float commission { get; set; }
    public float cost { get; set; }
    public string duration { get; set; }
    public bool extended_hours { get; set; }
    public int fees { get; set; }
    public string _class { get; set; }
    public int price { get; set; }
    public int quantity { get; set; }
    public DateTime request_date { get; set; }
    public bool result { get; set; }
    public string side { get; set; }
    public string status { get; set; }
    public string symbol { get; set; }
    public string type { get; set; }
}

用于反序列化的代码(来自 Newtonsoft 的 JSON.NET):

 Rootobject ord = JsonConvert.DeserializeObject<Rootobject>(responsebody);

我收到以下错误。

 Unhandled Exception: System.FormatException: Input string was not in a correct format.
   at Newtonsoft.Json.Utilities.ConvertUtils.Int32Parse(Char[] chars, Int32 start, Int32 length)
   at Newtonsoft.Json.JsonTextReader.ParseNumber()
   at Newtonsoft.Json.JsonTextReader.ParseValue()
   at Newtonsoft.Json.JsonTextReader.ReadInternal()
   at Newtonsoft.Json.JsonReader.ReadAsInt32Internal()
   at Newtonsoft.Json.JsonTextReader.ReadAsInt32()
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(Jso
nReader reader, JsonContract contract, Boolean hasConverter)

我尝试将反序列化的结果保存到工作正常的“动态”对象中。但我不想使用动态对象来映射字段。

请指教。

注意:第 3 方 API 也在发送一个名为“class”的字段。当我尝试直接调用该字段时出现编译时错误,我该如何调用它。

4

1 回答 1

7

您将类fees中的属性Order定义为 anint但在 JSon 文本中它是0.00000,即 afloatdouble。我认为您可能需要将fees属性变为 afloat才能正确解析它。pricequantity属性看起来也一样。

于 2013-11-26T10:31:36.573 回答