您可以使用地图来实现目标。在极端情况下(我的意思是,在你不想创建任何类的情况下),如果你想创建这个 json:
{
"sleep":{
"userInfo":{
"firstName":"Hans",
"lastName":"Schmidt",
"country":"Germany",
"city":"Berlin"
},
"settings":{
"setting2":"none",
"setting1":"y"
},
"program":{
"appVersion":"1.7",
"serverVersion":19,
"appName":"name"
},
"userType":"new"
}
}
你可以这样做:
Gson gson = new Gson();
Map<String, Object> finalObject= new HashMap<>();
Map<String, Object> sleep= new HashMap<>();
Map<String, Object> program= new HashMap<>();
Map<String, String> userInfo= new HashMap<>();
Map<String, Object> settings= new HashMap<>();
program.put("appName", "name");
program.put("appVersion", "1.7");
program.put("serverVersion", 19);
userInfo.put("firstName", "Hans");
userInfo.put("lastName", "Schmidt");
userInfo.put("city", "Berlin");
userInfo.put("country", "Germany");
settings.put("setting1", "y");
settings.put("setting2", "none");
sleep.put("program", program);
sleep.put("userType", "new");
sleep.put("userInfo", userInfo);
sleep.put("settings", settings);
finalObject.put("sleep", sleep);
System.out.println(gson.toJson(finalObject));
但是,正如另一个答案中所说,通常建议创建 POJO。
编辑
还有另一种方法可以做到这一点。使用 JsonObject 类:
JsonObject finalJsonObject= new JsonObject();
JsonObject jsonSleep= new JsonObject();
JsonObject jsonProgram= new JsonObject();
JsonObject jsonUserInfo= new JsonObject();
JsonObject jsonSettings= new JsonObject();
jsonUserInfo.addProperty("firstName", "Hans");
jsonUserInfo.addProperty("lastName", "Schmidt");
jsonUserInfo.addProperty("country", "Germany");
jsonUserInfo.addProperty("city", "Berlin");
jsonSettings.addProperty("setting2", "none");
jsonSettings.addProperty("setting1", "y");
jsonProgram.addProperty("appVersion", "1.7");
jsonProgram.addProperty("serverVersion", 19);
jsonProgram.addProperty("appName", "name");
jsonSleep.add("userInfo", jsonUserInfo);
jsonSleep.add("settings", jsonSettings);
jsonSleep.add("program", jsonProgram);
jsonSleep.addProperty("userType", "new");
finalJsonObject.add("sleep", jsonSleep);
System.out.println(String.valueOf(finalJsonObject));
如果您发现始终使用相同的代码,那么您应该创建类(以改进映射并消除重复)。如果有一些类您使用过几次,您可以使用这种方法(并避免创建您需要的每个类)。