0

I am trying to use the Json.Net converter for this strange json:

{
  "Key1": {
  "id": "1",
  "name": "one"
  },
  "Key2": {
  "id": "2",
  "name": "two"
  },
...
  "CouldBeAnything": {
  "id": "n",
  "name": "CouldBeAnything"
  }
}

If I use the json to xml source generation, I get objects with with properties called Key1, Key2 etc. That doesn't work as I need a list of those keys and values associated with them. Is there a way to create an object that can be serialized directly? Thanks in advance.

William
  • 69
  • 6
  • 1
    Use a `Dictionary` as explained [here](https://stackoverflow.com/a/24536564/3744182) or [here](https://stackoverflow.com/a/34213724/3744182). – dbc Jun 19 '17 at 21:02

1 Answers1

0

You could do something like this:

    class Class1
    {
        public string id { get; set; }
        public string name { get; set; }
    }

    static void Main(string[] args)
    {
        var d = new Dictionary<string, Class1>();

        d.Add("Key1", new Class1() { id = "1", name = "one" });
        d.Add("Key2", new Class1() { id = "2", name = "two" });
        d.Add("CouldBeAnything", new Class1() { id = "n", name = "CouldBeAnything" });

        var json = JsonConvert.SerializeObject(d, Formatting.Indented);

    }
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40