0

I'd like to build a json object which contains, among others, an array of objects like this:

{"ChoisiEvents":[{"Id_evt":25},{"Id_evt":4}],"parasite":3}

I have written some code like :

JSONArray JAChoisiEvents = new JSONArray();
JSONObject objEvent = new JSONObject();
try{
    if (cbxTemp.isChecked()){
          objEvent.put("Id_evt", 25);
          JAChoisiEvents.put(objEvent);
    }
    if (cbxAutreRaison.isChecked()) {
          objEvent.put("Id_evt", 4);
          JAChoisiEvents.put(objEvent);
    }
} catch (JSONException e) {
     e.printStackTrace();
}
//...
 JSONObject obj = new JSONObject();
 try {
   obj.put("parasite", iParasite); 
   System.out.println("ChoisiEvents : " + JAChoisiEvents.toString());
   obj.put("ChoisiEvents", JAChoisiEvents); //
  } catch (JSONException e) {
      e.printStackTrace();
  }

I got the following result:

{"ChoisiEvents":[{"Id_evt":4},{"Id_evt":4}],"parasite":3}

As you can see, the last item in my array is repeated each time !

2
  • Adding "Id_evt", 25 in JSONArray and getting {"Id_evt":6} in result ? Commented Mar 16, 2016 at 14:50
  • sorry, I correct my code (that's an extract). Commented Mar 16, 2016 at 14:51

1 Answer 1

1

You are using the same JSONObject, thats why value is overriding,

try to instantiate for the second time

objEvent = new JSONObject();

After adding to the first value.

Like this

JSONObject objEvent;

    if (cbxTemp.isChecked()){
         objEvent = new JSONObject();
          objEvent.put("Id_evt", 25);
          JAChoisiEvents.put(objEvent);
    }
    if (cbxAutreRaison.isChecked()) {
         objEvent = new JSONObject();
          objEvent.put("Id_evt", 4);
          JAChoisiEvents.put(objEvent);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Great, You've got the solution ! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.