ashek towhid
ashek towhid

Reputation: 21

Put method replacing the previous object of the jsonarray

I was trying to form this type of jsonarray.

[
 { 
  "userIdentity":"bbb",
  "admin":true/false
 },
 { 
  "userIdentity":"bbb",
  "admin":true/false
 }
.
.
.

        ]

I used this code in android giving input from a hashmap toAdd:

        JSONObject inerobj=new JSONObject();
        JSONArray jsonarray=new JSONArray();
        for (String s : toAdd.keySet()) {
        //  Log.d("userid",s);
          inerobj.put("userIdentity", s);
          inerobj.put("admin", Boolean.parseBoolean(toAdd.get(s)));
          Log.d("inerobj.toString",inerobj.toString());
          jsonarray.put(inerobj);
          Log.d("jsonarray.toString",jsonarray.toString());             
        }

the hashmap toAdd has:

towhid37:value=true
towhid32:value=true

in inerobj the value is ok.But when appending the inerobj to jsonarray, it adds 1st value(towhid37) ok. bt when it puts 2nd value(towhid32) it replaces 1st value also ie 1st element of the array now becomes (towhid32).

Heres Logcat output:

05-20 12:20:43.968: D/inerobj.toString(3788): {"admin":true,"userIdentity":"towhid37"}

05-20 12:20:43.988: D/jsonarray.toString(3788): [{"admin":true,"userIdentity":"towhid37"}]

05-20 12:20:43.988: D/inerobj.toString(3788): {"admin":true,"userIdentity":"towhid32"}

05-20 12:20:44.038: D/jsonarray.toString(3788): [{"admin":true,"userIdentity":"towhid32"},{"admin":true,"userIdentity":"towhid32"}]

What is the problem here?

Upvotes: 0

Views: 2126

Answers (1)

Naveen
Naveen

Reputation: 1703

add

inerobj=new JSONObject();

inside the for loop.

From what I understand, it stores the reference to the JSONObject instead of its values, that is why the values seems to be overwritten. Just re-initialize the variable to add new values.

Upvotes: 2

Related Questions