Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonProperty c# Serialize Dictionary values into an array

I have the following dictionary:

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

Actual behavior:

When I'm sending my data to the front I send it as an object:

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

Wanted Behavior

I want to send only the values of the dictionary as an array:

   "simulations": [
       {
            "rachatBrut": 542,
            "montantPercu": 250,
       },
       {
            "rachatBrut": 400,
            "montantPercu": 385,
       }
    ]
like image 776
Melchia Avatar asked Jun 04 '26 10:06

Melchia


1 Answers

You could either add another property and use [JsonIgnore] on the one u have right now. To make the new one an array just call .ToArray() on the Dictionary. Or you can write yourself an own CustomJsonConverter for this behavior.

For your specific case this would produce an array like the one u need:

Simulations.Select(k => k.Value).ToArray();
like image 52
aHochstein Avatar answered Jun 07 '26 08:06

aHochstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!