如何正确地将java对象转换为Json(嵌套)

时间:2016-02-12 16:48:32

标签: java json gson

好的,我想得到的输出是:

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

有没有人知道如何获得第一个结果?所以没有双引号。

3 个答案:

答案 0 :(得分:2)

使用此

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

而不是

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

结果应该是这样的:

"position": {
    "x": 10,
    "y": 50
  },

答案 1 :(得分:0)

JSONObject json = new JSONObject();
JSONArray addresses = new JSONArray();
JSONObject address;
try
{
   int count = 15;

   for (int i=0 ; i<count ; i++)
   {
       address = new JSONObject();
       address.put("Name","Name no." + i);
       address.put("Country", "Country no." + i);
       addresses.put(address);
   }
   json.put("Addresses", addresses);
}
catch (JSONException jse)
{
    out.println("Error during json formatting" + jse.getMessage());
}

我建议您使用JSONObject作为主JSON。之后,添加每个组件。对于矢量,添加一个json数组。这是一个我用来更好地理解这个例子的简单例子。

答案 2 :(得分:0)

您可以使用自己的java对象来精确。 Gson使用反射访问类中的字段,因此您不必手动解析任何内容。

例如在您的情况下:

    import com.google.gson.annotations.SerializedName;

    public class Walk {
        private int id;
        private Position position;

        @SerializedName("random-walk")
        private boolean randomWalk;

        @SerializedName("walk-radius")
        private int walkRadius;
    }
    public class Position {
        private int x,y,z;
    }

然后使用

 Gson gson = new Gson();
 Walk walk = gson.fromJson(yourJson, Walk.class);
相关问题