2017-04-20 108 views
1

我的問題很簡單,我想添加一個JSONObject到存儲在MongoDB數據庫中的JSONArray。我可以輕鬆地添加所有類型的數據,如Strings,Ints等,但不是JSONObjects。 我這樣做在我的代碼:Parse.com將JSON對象添加到JSON數組

public void done(ParseObject lan, ParseException e) { 
    if(e==null){ 
     JSONObject object = new JSONObject(); 
     try{             
      object.put("PlayerName","John"); 
      object.put("ID",514145);             
      lan.add("Participants",object); //nothing gets inserted 
      lan.add("Participants",15); //works fine 
      lan.add("Participants",JSONObject.null); //works fine too 
      }catch (JSONException error){ 

      } 

      lan.increment("Number"); 
      lan.saveInBackground(); 
    }else{ 
      Log.i("Parse Error","error"); 
    } 
} 

但沒有出現在我的數據庫,並沒有拋出錯誤。 你們有什麼線索怎麼做?

+0

你可以嘗試'JSONArray jsonArray =新JSONArray(); jsonArray.put(對象); jsonArray.put(15); jsonArray.put(JSONObject.null); lan.put(「Participants」,jsonArray)'而不是直接添加到'ParseObject'? – Veeram

+0

我試過了,但在我的情況下,我想能夠添加多個對象到我的數組。如果我這樣做,它將用一個新陣列取代陣列... –

+0

好的。我不知道爲什麼你在帖子中的方式不起作用。有沒有辦法可以得到'JSONArray jsonArray = getExistingArrayFromParseObject;'然後添加新條目。 – Veeram

回答

2

嘗試使用object.toString()而不是object

lan.add("Participants", object.toString()); 

JSON:

{"Participants":["{\"PlayerName\":\"John\",\"ID\":514145}"]} 

解析這個JSON試試這個:

JSONObject jsonObj = new JSONObject(YOUR_JSON_STRING); 

// Participants 
JSONArray participantsJsonArray = jsonObj.getJSONArray("Participants"); 

// Participant 
JSONObject participanJsonObject = participantsJsonArray.getJSONObject(0); 

// PlayerName 
String playerName = participanJsonObject.getString("PlayerName"); 
// ID 
String id = participanJsonObject.getInt("ID"); 

希望這將有助於〜

+0

好的,謝謝你的工作,但在數據庫中它看起來像這樣:「{\」PlayerName \「:\」John \「,\」ID \「:514145}」。它不是很乾淨! –

+1

我已經用JSON解析更新了答案。試試這個 – FAT

+1

如果我的回答看起來有用,那麼請給出一個upvote。閱讀http://stackoverflow.com/help/someone-answers – FAT

1

轉換是JSON對象爲字符串,並將其存儲在字符串格式

lan.add("Participants",object.toString()); 

而當你想用,你可以很容易地將其轉換成JSON對象再這樣

JSONObject jObj=new JSONObject("Your Json String"); 
+0

好吧,謝謝你的工作,但在數據庫中它看起來像這樣:「{\」PlayerName \「:\」John \「,\」ID \「:514145}」。它不是很乾淨! –

+0

嘗試將其轉換回來,並檢查是否獲得相同的對象 – AbhayBohra

+0

但是,如何檢索它?在數據庫中是這樣的:「參與者」:[ 「{\」PlayerName \「:\」John \「,\」ID \「:514145}」 ], –