序列化名为“return”的JSON对象

时间:2013-01-25 18:08:51

标签: c# json json.net

我正在尝试针对Mt Gox的Http API撰写自动收录器。它返回如下所示的JSON:

{
"result":"success",
"return":
 {
 "high": {"value":"5.70653","value_int":"570653","display":"$5.70653","currency":"USD"},
 "low": {"value":"5.4145","value_int":"541450","display":"$5.41450","currency":"USD"},
 "avg": {"value":"5.561119626","value_int":"556112","display":"$5.56112","currency":"USD"},
 "vwap": {"value":"5.610480461","value_int":"561048","display":"$5.61048","currency":"USD"},
 "vol": {"value":"55829.58960346","value_int":"5582958960346","display":"55,829.58960346\u00a0BTC","currency":"BTC"},
 "last_all":{"value":"5.5594","value_int":"555940","display":"$5.55940","currency":"USD"},
 "last_local":{"value":"5.5594","value_int":"555940","display":"$5.55940","currency":"USD"},
 "last_orig":{"value":"5.5594","value_int":"555940","display":"$5.55940","currency":"USD"},
 "last":{"value":"5.5594","value_int":"555940","display":"$5.55940","currency":"USD"},
 "buy":{"value":"5.53587","value_int":"553587","display":"$5.53587","currency":"USD"},
 "sell":{"value":"5.56031","value_int":"556031","display":"$5.56031","currency":"USD"}
 }
}

我正在尝试将该信息转换为对象。我创建了一组看起来像这样的类:

[DataContract]
class MtGoxResponse
{
    public string result { get; set; }
    [DataMember(Name="return")]
    public Resp Resp { get; set; }
}

[DataContract]
class Resp
{
    public HLA high { get; set; }
    public HLA low { get; set; }
    public HLA avg { get; set; }
    public HLA vwap { get; set; }
    public HLA vol { get; set; }
    public HLA last_all { get; set; }
    public HLA last_local { get; set; }
    public HLA last_orig { get; set; }
    public HLA last { get; set; }
    public HLA buy { get; set; }
    public HLA sell { get; set; }
}

[DataContract]
class HLA
{
    public double value { get; set; }
    public int value_int { get; set; }
    public string display { get; set; }
    public string currency { get; set; }
}

Result每次都很好,但Resp始终为空。我错过了DataContract属性的内容吗?我假设根本原因是对象的名称,但肯定有办法绕过它。

1 个答案:

答案 0 :(得分:4)

我不确定您的[DataMember]属性无效的原因。根据我的阅读,[DataMember]似乎对每个序列化程序的实现都有不同的解释,所以它可能是一个错误。

但是,您只需在@之前使用return符号即可消除使用它的需要,如下所示:

[DataContract]
class MtGoxResponse
{
    public string result { get; set; }
    public Resp @return { get; set; }
}

这个前缀在MSDN的C# keywords页面上被动地提到。