Search code examples
javajsongsonuser-inputjavascript-objects

How can I use objects as keys in a JSON?


I have this neat data format which is best represented with objects as keys. So I tried to use the following JSON:

{
  "blocks": {
    "stone": {
      {
        "variant": ["bricks", "smooth"]
      }: {
        "sound": "guitar",
        "particle": "guitar",
      }
    },
    "dirt": {
      {
        "variant": "dirt"
      }: {
        "sound": "square",
        "particle": "note",
        "volume": 0.5
      }
    }
  }
}

But it gives me a JsonSyntaxException. I'm using GSON btw. How can I make this work?

The data structures:

import java.util.*;
public class Instrument {
  private final String name;
  private final String particle;
  private final float volume;
  public Instrument(String name, Optional<String> particle, Optional<Float> volume) {
    this.name = name;
    this.particle = particle.orElse("note");
    this.volume = volume.orElse(1.0f);
  }
  /* getters and stuff */
}

public class BlockType {
  private final String name;
  private final BlockStateMatcher state;
  public BlockType(String name, BlockStateMatcher state) {
    this.name = name;
    this.state = state;
  }
  /* getters and stuff */
}

import java.util.*;
public class BlockStateMatcher {
  private final Map<PropertyMap, Instrument> states;
  /* etc */
}

import java.util.*;
public class PropertyMap extends HashMap<Property<T>, List<PropertyValue<T>>> /* simplified */ {
  /* etc */
}

Solution

  • You can't. It's not valid JSON syntax.

    As per the documentation, the object keys need to be strings, and according to the spec:

    An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string.