如何以特定格式编写json文件?

时间:2015-06-28 12:35:48

标签: java json nullpointerexception

我几乎完成了我的程序,它加载完美但我遇到的一个问题是当我通过我的程序编辑json文件时,我无法重新加载json文件,因为当我保存文件时,格式变得不同。

所以我的问题是我如何格式化json文件,就像我读它一样?

这是我写新json文件的方法。

    public static boolean write(File npcDefFile) {
    try {
        FileWriter writer = new FileWriter(npcDefFile);
        Throwable localThrowable3 = null;
        try {
            Gson gson = new Gson();
            String json = gson.toJson(NPCDefinitions.getNPCDefinitions());
            writer.write(json);
            writer.flush();
        } catch (Throwable localThrowable1) {
            localThrowable3 = localThrowable1;
            throw localThrowable1;
        } finally {
            if (writer != null) {
                if (localThrowable3 != null) {
                    try {
                        writer.close();
                    } catch (Throwable localThrowable2) {
                        localThrowable3.addSuppressed(localThrowable2);
                    }
                } else {
                    writer.close();
                }
            }
        }
    } catch (NullPointerException | IOException e) {
        System.out.println(e.getLocalizedMessage());
        return false;
    }
    return true;
}

这里的格式正确(3空格标签)

    [
  {
    "id": 0,
    "name": "Hans",
    "examine": "Servant of the Duke of Lumbridge.",
    "combat": 0,
    "size": 1,
    "attackable": false,
    "aggressive": false,
    "retreats": false,
    "poisonous": false,
    "respawn": 10,
    "maxHit": 0,
    "hitpoints": 0,
    "attackSpeed": 7,
    "attackAnim": 0,
    "defenceAnim": 0,
    "deathAnim": 0,
    "attackBonus": 0,
    "defenceMelee": 0,
    "defenceRange": 0,
    "defenceMage": 0
  },
  {
    "id": 1,
    "name": "Man",
    "examine": "One of Wildy's many citizens.",
    "combat": 2,
    "size": 1,
    "attackable": true,
    "aggressive": false,
    "retreats": true,
    "poisonous": false,
    "respawn": 10,
    "maxHit": 1,
    "hitpoints": 7,
    "attackSpeed": 7,
    "attackAnim": 422,
    "defenceAnim": 1834,
    "deathAnim": 836,
    "attackBonus": 9,
    "defenceMelee": 9,
    "defenceRange": 9,
    "defenceMage": 0
  }
]

这是我将文件保存到新的json文件后的格式。 (压缩)

[{"id":0,"name":"Hans","examine":"Servant of the Duke of               Lumbridge.","combat":0,"size":1,"attackable":false,"aggressive":false,"retreats":false,"poisonous":false,"respawn":10,"maxhit":0,"hp":0,"attackspeed":7,"attackanim":0,"defenceanim":0,"deathanim":0,"attackbonus":0,"defencemelee":0,"defencerange":0,"defencemage":0},{"id":1,"name":"Man","examine":"One of Wildy\u0027s many citizens.","combat":2,"size":1,"attackable":true,"aggressive":false,"retreats":true,"poisonous":false,"respawn":10,"maxhit":1,"hp":7,"attackspeed":7,"attackanim":422,"defenceanim":1834,"deathanim":836,"attackbonus":9,"defencemelee":9,"defencerange":9,"defencemage":0}]

这就是我加载json文件的方式。

    /**
 * A dynamic method that allows the user to read and modify the parsed data.
 *
 * @param reader
 *            the reader for retrieving the parsed data.
 * @param builder
 *            the builder for retrieving the parsed data.
 */
public abstract void load(JsonObject reader, Gson builder);

/**
 * Loads the parsed data. How the data is loaded is defined by
 * {@link JsonLoader#load(JsonObject, Gson)}.
 *
 * @return the loader instance, for chaining.
 */
public final JsonLoader load() {
    try (FileReader in = new FileReader(Paths.get(path).toFile())) {
        JsonParser parser = new JsonParser();
        JsonArray array = (JsonArray) parser.parse(in);
        Gson builder = new GsonBuilder().create();

        for (int i = 0; i < array.size(); i++) {
            JsonObject reader = (JsonObject) array.get(i);
            load(reader, builder);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return this;
}

任何帮助都将不胜感激。

编辑:

这是一个被抓住的例外。

java.lang.NullPointerException
at NpcDefinitionLoader.load(NpcDefinitionLoader.java:28)
at JsonLoader.load(JsonLoader.java:56)
at NPCDefinitions.loadNPCDefinitions(NPCDefinitions.java:76)
at DefinitionEditor.loadFile(DefinitionEditor.java:171)
at DefinitionEditor.loadButtonActionPerformed(DefinitionEditor.java:790)
at DefinitionEditor.actionPerformed(DefinitionEditor.java:827)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased

这是发生错误的第一行。

int maxHit = reader.get("maxHit").getAsInt();

第二行错误

load(reader, builder);

1 个答案:

答案 0 :(得分:0)

您的JSON对象键以小写形式保存。 JSON区分大小写。

在压缩文件中,它有 maxhit 而不是 maxHit 。检查 NpcDefinitions ,了解该字段/属性的声明方式。

可以使用Gson.toJson(JsonElement,JsonWriter)完成使用Gson打印JSON。这里的文档中有一个很好的缩进示例: https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonWriter.html