我有一個POJO類爲:JSON越來越嵌套在一個POJO
public class D{
private JSONObject profileData;
public JSONObject getProfileData()
{
return profileData;
}
public void setProfileData (JSONObject profileData)
{
this.profileData = profileData;
}
}
現在我填充這個類,如:
for (int i =0; i<identities.size();i++){
D d = new D();
d.setProfileData(profileData);
dList.add(d);
}
我用一個HashMap創建JSON對象profileData
從GSON:
profileDataInJson = new JSONObject(gson.toJson(map1));
其中profileDataInJson的簽名是:JSONObject profileDataInJson = null;
現在得到的JSON是這樣的:
"profileData":{"map":{"ioCinema":"firstValue","ioSIMAvailable":"firstKey","Name":"onePair"}}
其中,我會得到一個名爲地圖插在我的主要profileData對象不需要的對象。
但是當我打印這個循環中,我得到
{`"ioCinema":"firstValue","ioSIMAvailable":"firstKey","Name":"onePair"}`
韋思正是我想要profileData對象中,沒有嵌套map
對象。
我該如何解決這個問題?
「我已經知道從JSONObject的轉換profileData的類型,d類的字符串,這將導致轉義字符,我可以做到這一點 - 但我要尋找一個通用的解決方案」
編輯:
MAP1被構造以兩種方式,這取決於用戶輸入和兩種方式如下:
if (args.length >= 4 && args[1].equalsIgnoreCase("onePair")) {
map1 = new HashMap<>();
String key1 = args[2];
String value1 = args[3];
map1.put(key1, value1);
profileDataInJson = new JSONObject(gson.toJson(map1));
}
和:
if (args.length >= 1 && args[0].equalsIgnoreCase("update")) {
if (args.length >= 2)
profileData.setName(args[1] != null ? args[1] : "");
if (args.length >= 3)
profileData.setSIMAvailable(args[2] != null ? args[2] : "");
profileDataInJson = new JSONObject(profileData);
}
簽名:ProfileData profileData = new ProfileData();
這讓我爲難的事情是,當我試圖穿越profileData並嘗試通過名稱來獲取JSON對象「地圖」我得到一個空指針異常
GSON不知道org.json.JSONObject'的'和其序列如根據其內部結構是由反射。將其替換爲'com.google.gson.JsonObject'。 –