【问题标题】:JsonProperty c# Serialize Dictionary values into an arrayJsonProperty c# 将字典值序列化为数组
【发布时间】:2019-02-27 12:59:39
【问题描述】:

我有以下字典:

   [JsonProperty("Simulations")]
    public IDictionary<int, Simulation> Simulations { get; set; }

实际行为:

当我将数据发送到前端时,我将其作为对象发送:

   "simulations": {
       "02": {
            "rachatBrut": 542,
            "montantPercu": 250,
            },
        "52": {
            "rachatBrut": 400,
            "montantPercu": 385,
            },
    }

想要的行为

我只想将字典的值作为数组发送:

   "simulations": [
       {
            "rachatBrut": 542,
            "montantPercu": 250,
       },
       {
            "rachatBrut": 400,
            "montantPercu": 385,
       }
    ]

【问题讨论】:

  • JsonIgnore 现有属性。创建一个新的只读属性,该属性在 JSON 中投影您想要的数组。

标签: c# json asp.net-core deserialization


【解决方案1】:

您可以添加另一个属性并在您现在拥有的属性上使用 [JsonIgnore]。要使新数组成为数组,只需在 Dictionary 上调用 .ToArray() 即可。 或者您可以为此行为写一个自己的CustomJsonConverter

对于您的具体情况,这将生成一个您需要的数组:

Simulations.Select(k => k.Value).ToArray();

【讨论】:

  • 它产生一个包含 KeyValuePair 对象的数组。如果你只想要你需要使用 Select 之前的值。
  • 谢谢。我最终将我的字典转换成一个模拟数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-10
相关资源
最近更新 更多