【发布时间】:2015-03-03 16:50:59
【问题描述】:
作为我正在创建的 API 的一部分,我允许配置规范(可以是任何存储格式,只有一种实现是使用 Json)。作为其中的一部分,我的代码将不知道配置的真正含义。 我正在使用 Gson 库来读取 json 实现的配置,但是我在如何处理数字方面遇到了障碍。 我当前的代码使用递归来读取内部对象,并包含以下内容:
private JsonConfigurationSection readObject(JsonReader in) throws IOException {
JsonConfigurationSection section = new JsonConfigurationSection();
in.beginObject();
while (in.peek() != JsonToken.END_OBJECT) {
String name = in.nextName();
switch (in.peek()) {
case BEGIN_OBJECT: {
section._internal.put(name, readObject(in));
}
break;
case BEGIN_ARRAY: {
in.beginArray();
List<String> array = new LinkedList<>();
while (in.peek() != JsonToken.END_ARRAY) {
array.add(in.nextString());
}
in.endArray();
section._internal.put(name, array);
}
break;
case BOOLEAN: {
boolean next = in.nextBoolean();
section._internal.put(name, next);
}
break;
case NUMBER: {
//read the next number, whether long, int, or double
section._internal.put(name, next);
}
break;
case STRING: {
String next = in.nextString();
section._internal.put(name, next);
}
break;
}
}
in.endObject();
}
JsonConfigurationSection 类只是一个 Map 的包装器:
class JsonConfigurationSection implements ConfigurationSection {
final Map<String, Object> _internal = new TreeMap<>();
//methods being inherited, just getters for data from the map
}
一个配置示例可能是
{
"server": {
"ip": "127.0.0.1",
"port": 3306
}
"someval": 33.4
}
出现的问题是 JsonReader 只为“数字”提供下一个标记,但随后为 long、double 和 ints 提供特定的 getter。
在不丢失任何数据并使用“最佳”存储空间的情况下获得该数字的最佳方法是什么? (我愿意放弃多头,但更愿意看看我是否可以保持它们的一致性)
【问题讨论】:
-
我不太了解这个库,但你可以调用
nextString来获取号码,然后将该值传递给新的BigDecimal并让BigDecimal确定它是否是双精度或整数。 -
我曾考虑过转换,但这对我来说似乎有点难看,有点希望有其他方法可以更“原生”地工作
标签: java json gson jsonreader