如何在JSON中使用对象作为键?

时间:2016-10-28 00:59:44

标签: java json gson user-input javascript-objects

我有这种整洁的数据格式,最好用对象作为键来表示。所以我尝试使用以下JSON:

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

但它给了我一个JsonSyntaxException。我正在使用GSON btw。我怎样才能做到这一点?

数据结构:

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 */
}

2 个答案:

答案 0 :(得分:5)

你不能。它不是有效的JSON语法。

根据documentation,对象键需要是字符串,并且根据spec

  

对象结构表示为一对花括号   包含零个或多个名称/值对(或成员)。名字是   字符串。

答案 1 :(得分:1)

您提供的文字无效json。

如果您的文字是

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

你可以解析它。