如何使用 Gson 读取没有值的 json?

How to read a json without a value with Gson?

我用 GSON 库读取了一个 json 文件。 我使用以下代码:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);

一切正常,如果我的 json 具有所有值,但如果 json 中缺少某些值,例如下面的 json,我会得到一个异常。

com.google.gson.stream.MalformedJsonException: 
Expected value at line 1 column 217 path $.repeatInterval

.

{
  "key1": "a",
  "key2": "",
  "key3": 
}

如何在使用 GSON 库时读取 json 包含缺失值的文件?

编辑: 解决无一例外。添加 "key3:""

{
  "key1": "a",
  "key2": "",
  "key3": ""
}

你的 json 是无效的,你可以在这个网站上看到例如: http://jsonlint.com/ 据我所知,GSON 总是会在无效的 JSON 上抛出异常,那就是预期的行为。 如果您可以创建 JSON,请至少尝试使用 "" 而不是空值,以符合 JSON 格式。