Serialize JSON object named “return”

我只是一个虾纸丫 提交于 2019-12-07 07:35:22

问题


I'm trying to write a ticker against Mt Gox's Http API. It returns JSON that looks like this:

{
"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"}
 }
}

I'm trying to cast that information into an object. I've made a set of classes that look like this:

[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 comes through fine every time, but Resp is always null. Am I missing something with the DataContract attributes? I'm assuming the root cause is the object's name, but surely there's a way around it.


回答1:


I'm not sure exactly why your [DataMember] attribute isn't working. From what I've read, [DataMember] appears to be interpreted differently per implementation of serializers, so it may well be a bug.

However, you can remove the need of using it by simply using the @ sign before return, like so:

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

This prefix is mentioned somewhat passively on MSDN's page for C# keywords.



来源:https://stackoverflow.com/questions/14527804/serialize-json-object-named-return

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!