2017-04-20 106 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}” ], –