好了,所以我希望得到的輸出是這樣的:如何將Java對象正確地轉換成JSON(嵌套)
{
"id": 460,
"position": {
"x": 3078,
"y": 3251,
"z": 0
},
"random-walk": true,
"walk-radius": 1
},
但我目前得到的是:
{
"id": 460,
"position": "{
"x": 3078,
"y": 3251,
"z": 0
}",
"random-walk": true,
"walk-radius": 0
},
問題是我試圖轉換爲json的位置對象。 代碼我想:
Path path = Paths.get("./npcs.json");
File file = path.toFile();
file.getParentFile().setWritable(true);
if (!file.getParentFile().exists()) {
try {
file.getParentFile().mkdirs();
} catch (SecurityException e) {
System.out.println("Unable to create directory for donator data!");
}
}
try (FileWriter writer = new FileWriter(file)) {
Gson builder = new GsonBuilder().setPrettyPrinting().create();
JsonObject object = new JsonObject();
Position pos = new Position(mob.absX, mob.absY, mob.heightLevel);
object.addProperty("id", mob.npcId);
object.addProperty("position", builder.toJson(pos));
object.addProperty("random-walk", mob.randomWalk);
object.addProperty("walk-radius", mob.walkingType);
writer.write(builder.toJson(object));
writer.close();
} catch (Exception e) {
System.out.println("Something went wrong with saving for mob !");
e.printStackTrace();
}
有沒有人有關於如何得到第一個結果的線索?所以沒有雙引號。
的toJSON是否會返回一個JSON,而不是對象。 –
@DaveNewton我明白了,你能告訴我如何正確地做到這一點嗎? –