Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly convert java object to Json (Nested)

Tags:

java

json

gson

Okay so the output I would like to get is this:

  {
    "id": 460,
    "position": {
      "x": 3078,
      "y": 3251,
      "z": 0
    },
    "random-walk": true,
    "walk-radius": 1
  },

But the one I currently get is:

{
  "id": 460,
  "position": "{
    "x": 3078,
    "y": 3251,
    "z": 0
  }",
  "random-walk": true,
  "walk-radius": 0
},

The problem is the position object that I am trying to convert to json. The code I tried:

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();
}

Does anyone has a clue on how to get the first result? So without the double-quotes.

like image 820
StanGaming 666 Avatar asked Mar 09 '26 09:03

StanGaming 666


1 Answers

Use this

object.add("position", new Gson().toJsonTree(pos));

instead of

object.addProperty("position", builder.toJson(pos));

result should than look like this:

"position": {
    "x": 10,
    "y": 50
  },
like image 76
Patrick Avatar answered Mar 11 '26 22:03

Patrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!