2017-03-14 59 views
0

我有一個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對象「地圖」我得到一個空指針異常

+0

GSON不知道org.json.JSONObject'的'和其序列如根據其內部結構是由反射。將其替換爲'com.google.gson.JsonObject'。 –

回答

2

你並不需要使用Gson將hashmap轉換爲json對象。 只需使用:

profileDataInJson = new JSONObject(map);

+0

我仍然得到相同的結果! – User3

+0

@ User3你可以發佈你正在構建'map1'對象的代碼嗎? –

+0

請檢查編輯 – User3

0

添加自定義序列化GSON,使GSON序列化JSON組織通過你預期。

GsonBuilder gsonBuilder = new GsonBuilder(); 
gsonBuilder.registerTypeAdapter(JSONObject.class, new JsonSerializer<JSONObject>() { 
      @Override 
      public JsonElement serialize(final JSONObject src, final Type typeOfSrc, 
        final JsonSerializationContext context) { 
       return new JsonParser().parse(src.toString()).getAsJsonObject(); 
      } 
     }); 
gsonBuilder.create().toJson(map1); 

這將返回{"ioCinema":"firstValue","ioSIMAvailable":"firstKey","Name":"onePair"}