【问题标题】:Why is my object null when trying to parse a json string to said object [duplicate]尝试将json字符串解析为所述对象时,为什么我的对象为空[重复]
【发布时间】:2020-03-11 02:42:36
【问题描述】:

我正在尝试解析一些如下所示的 json 数据:

{
  "2": {
    "id": 2,
    "name": "Cannonball",
    "members": true,
    "sp": 5,
    "buy_average": 172,
    "buy_quantity": 210800,
    "sell_average": 174,
    "sell_quantity": 326435,
    "overall_average": 174,
    "overall_quantity": 537235
  },
  "6": {
    "id": 6,
    "name": "Cannon base",
    "members": true,
    "sp": 187500,
    "buy_average": 185130,
    "buy_quantity": 1,
    "sell_average": 181300,
    "sell_quantity": 3,
    "overall_average": 182257,
    "overall_quantity": 4
  }
}

我正在使用以下模型

class BuySellModel
{
    public int id { get; set; }
    public string name { get; set; }
    public bool members { get; set; }
    public int sp { get; set; }
    public int buy_average { get; set; }
    public int buy_quantity { get; set; }
    public int sell_average { get; set; }
    public int sell_quantity { get; set; }
    public int overall_average { get; set; }
    public int overall_quantity { get; set; }
}

现在我尝试解析它的方式是使用 JSON.NET 以将每个项目作为 .NET 对象获取到某种集合中,有点像List<BuySellModel>

但是..当我尝试解析它时

var BuySellObjects = JsonConvert.DeserializeObject<BuySellModel>(buySellDataString);

BuySellObjects 中的每个属性都为空,我不明白为什么。

有人可以解释为什么每个属性都为空,而我在这里出错了吗?

【问题讨论】:

  • name以外的属性不能为空。
  • 您的 json 字符串有一个具有 2 属性和 6 属性的对象。
  • 哦!我现在看到了,但是我该如何解决呢?它会是一个模型,里面有一个模型吗?有点迷茫

标签: c# .net json json.net


【解决方案1】:

试着用这个作为你的模型

    public class ParsableModel
    {
       public Dictionary<int, BuySellModel> BuySellObjects { get; set; }
    }

【讨论】:

    【解决方案2】:

    你的 json 看起来像一个 int 和 BuySellModel 的字典

    你可以试试这个

    var dictionary = JsonConvert.DeserializeObject<IDictionary<int, BuySellModel>>(buySellDataString);
    var allBuySellObjects = dictionary.Values; // flatten all the values into a list
    

    【讨论】:

      猜你喜欢
      • 2017-08-17
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多