【问题标题】:C# json deserialization to dictionary (Json.NET)C# json 反序列化为字典 (Json.NET)
【发布时间】:2018-02-04 22:48:28
【问题描述】:

问题

嗨,请帮我将 Json 反序列化为 C# 字典,其中 KeyValuePair 的键 = 'symbol' 的值,而 'cur' 我不想反序列化。

我的 JSON

[
  {
    "cur": "BNT",
    "symbol": "BNT/BTC",
    "last": 0.00069999,
    "high": 0.000725,
    "low": 0.000631,
    "volume": 11.83176914,
    "vwap": 0.00066075,
    "max_bid": 0.000725,
    "min_ask": 0.000631,
    "best_bid": 0.00062001,
    "best_ask": 0.0007
  },
  {
    "cur": "FST",
    "symbol": "FST/BTC",
    "last": 0.00000113,
    "high": 0.00000136,
    "low": 0.0000011,
    "volume": 105727.64821274,
    "vwap": 0.00000115,
    "max_bid": 0.0000012,
    "min_ask": 0.00000108,
    "best_bid": 0.00000115,
    "best_ask": 0.00000127
  }
]

C#

public class SomeClass
{
    Dictionary<string,Ticker> dictionary { get; set; }
}

public class Ticker
{
    public decimal Last { get; set; }

    public decimal High { get; set; }

    public decimal Low { get; set; }

    public decimal Volume { get; set; }

    public decimal Vwap { get; set; }

    public decimal MaxBid { get; set; }

    public decimal MinAsk { get; set; }

    public decimal BestBid { get; set; }

    public decimal BestAsk { get; set; }
}

我想我需要使用 CustomCreationConverter,但我不知道该怎么做 :)

谢谢

【问题讨论】:

标签: c# json dictionary


【解决方案1】:

您的 json 是一个数组/列表。反序列化为

List<Ticker>

不是字典。

一个更正确的模型应该是

public class Ticker
{
    public string cur { get; set; }
    public string symbol { get; set; }
    public double last { get; set; }
    public double high { get; set; }
    public double low { get; set; }
    public double volume { get; set; }
    public double vwap { get; set; }
    public double max_bid { get; set; }
    public double min_ask { get; set; }
    public double best_bid { get; set; }
    public double best_ask { get; set; }
}

var list = JsonConvert.DeserializeObject<List<Ticker>>(jsonstring);

如果你真的需要一本字典

var dict = list.ToDictionary(x => x.symbol, x => x);

【讨论】:

  • 我认为 symbol 应该是关键,否则他们不会知道数据代表什么......但谁知道呢,它问得太差了。
  • 不,我需要在字典中反序列化它。然后我可以很容易地提取所需的货币对,例如: Ticker ticker = dict["BTC/USD];
  • @N.Kit 我也将它包含在我的答案中。再读一遍(当然可以用一些 json.net 技巧来完成,比如 JsonConverter,但是 2 行解决方案更容易理解和维护)
  • @Eser 抱歉,我没看到 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 2014-02-19
  • 2011-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多