Parse.com 添加 JSON 对象到 JSON 数组

Parse.com add JSON Object to JSON Array

我的问题很简单,我想将 JSONObject 添加到存储在 MongoDB 数据库中的 JSONArray。我可以轻松添加所有类型的数据,例如 StringsInts 等,但不能添加 JSONObjects。 我在我的代码中这样做:

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");
   }
}

但是我的数据库中什么也没有出现,也没有抛出任何错误。 你们知道如何做到这一点吗?

将 Json 对象转换为字符串并以字符串格式存储

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

当你想使用它时,你可以像这样轻松地将它再次转换成 Json 对象

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

尝试使用 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");

希望对你有所帮助~