您可以使用地圖,以實現這一目標。在極端情況下(我的意思是,在情況下,你不希望創建任何類),如果你想創建這個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));
如果您發現您總是使用相同的代碼,那麼你應該創建類(以提高測繪和消除重複)。如果有幾個類使用幾次,可以使用這種方法(並避免創建您需要的每個類)。
問題是什麼,gson會爲你做這個工作嗎? –
如果你想要一個你的json的pojo表示,那麼你需要像你所建議的那樣爲不同的樹級別設置不同的類。如果你不需要,你可能可能(我不知道Gson,但我認爲它與Jackson非常相似),也可以使用maps/JSONObject實例和列表/ JSONArray實例的組合。 – Thomas
,你可以編寫課程並相互實現,然後gson將完成這項工作 –