Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# json object for dynamic properties

Tags:

json

c#

I need to output this json:

{
      white: [0, 60],
      green: [60, 1800],
      yellow: [1800, 3000],
      red: [3000, 0]
}

And I was trying to think on a model like:

 public class Colors
    {

        public int[] white { get; set; }

        public int[] green { get; set; }

        public int[] yellow { get; set; }

        public int[] red { get; set; }
    }

But the property names could change, like maybe white can be now gray, etc.

Any clue?

like image 271
VAAA Avatar asked Nov 14 '25 10:11

VAAA


1 Answers

All you need is a Dictionary:

Dictionary<string, int[]> dictionary = new Dictionary<string, int[]>();

dictionary.Add("white", new int[] { 0, 60 });
dictionary.Add("green", new int[] { 60, 1800 });
dictionary.Add("yellow", new int[] { 1800, 3000 });
dictionary.Add("red", new int[] { 3000, 0 });

//JSON.NET to serialize
string outputJson = JsonConvert.SerializeObject(dictionary)

Results in this json:

{
    "white": [0, 60],
    "green": [60, 1800],
    "yellow": [1800, 3000],
    "red": [3000, 0]
}

Fiddle here

like image 112
maccettura Avatar answered Nov 17 '25 05:11

maccettura