Search code examples
c#.netdictionarygraphqlgraphql-dotnet

Can I represent my .NET dictionaries as JSON dictionaries in my GraphQL?


When I'm serialising to JSON, I'm used to .NET dictionaries becoming objects with the keys as properties and the values as their values. (The Json.Net docs have a succinct example.)

I'm using GraphQL and struggling to achieve a similar result. My data for this root query is basically a Dictionary<MyEnum,Dictionary<string,string>>. The closest I've got so far is this:

{
  "data": {
    "outterDict": [
      {
        "key": "THING_1",
        "innerDict": [
          {
            "key": "key1",
            "val": "val1"
          },
          ...
        ]
      },
      {
        "key": "THING_2",
        "innerDict": [
          {
            "key": "key2",
            "val": "val2"
          },
          ...
        ]
      }
    ]
  }
}

But I want it to be closer to this:

{
  "data": {
    "collection": {
      "THING_1": {
        "key1": "val1",
        ...
      },
      "THING_2": {
        "key2": "val2",
        ...
      }
    }
  }
}

I'm struggling because GraphQL .Net only seems to understand lists, not dictionaries.

It doesn't feel like what I'm trying to do is unreasonable. Letting keys be keys seems right and like the most useful way to share this data (e.g. as suggested by this answer).

Is there a way to do this in GraphQL? Is there a way to do this in GraphQL .Net?


Solution

  • After quite of lot of research, it seems like this isn't in the spec of GraphQL and is therefore unsupported in GraphQL.Net.

    GraphQL expects all possible properties (i.e. keys in a map/dictionary) to be known in advance. This means we lose a lot of the value of passing a dictionary at run time.

    So although the GraphQL JSON is more verbose than idiomatic JSON, it's like this deliberately.