Samantha Prabhu
Samantha Prabhu

Reputation: 1

Overriding of values in Json object

I am trying to generate key value pair JSON format, but it gets overwritten, Could anyone help me please

Program

JSONObject jobj = new JSONObject();
List<JSONObject> json = new ArrayList<>();
ListIterator l = desc.listIterator();// desc is an arraylist and has some values
ListIterator l2 = amts.listIterator();//amts ia an arraylist and has some values

while (l.hasNext() && l2.hasNext()) {
    jobj.put("Des", l.next());
    jobj.put("Amount", l2.next());
    json.add(jobj);//trying to add json to combine two object into single object
    System.out.println("Datas of jsons" + json);//values are overriding
}

Expected output:

[
 {"Des":"Mani","Amount":846},
 {"Des":"Shiva","Amount":900},
 {"Des":"Sam","Amount":23}, 
 {"Des":"Rajashree","Amount":923},
 {"Des":"Kokila","Amount":86}, 
 {"Des":"Samantha","Amount":12}
]

Output I am getting

[
 {"Des":"Mani","Amount":846}, 
 {"Des":"Mani","Amount":846}, 
 {"Des":"Mani","Amount":846}, 
 {"Des":"Mani","Amount":846}, 
 {"Des":"Mani","Amount":846}, 
 {"Des":"Mani","Amount":846}
]

I am new to java if it is a silly question plz don't block me

Upvotes: 0

Views: 1859

Answers (1)

Defaulter
Defaulter

Reputation: 368

Try moving your JSONObject initialization from outside of while loop to inside of it. As shown below

while(l.hasNext() && l2.hasNext()){
  JSONObject jobj = new JSONObject();
  jobj.put("Des",l.next());
  jobj.put("Amount",l2.next());
  json.add(jobj);//trying to add json to combine two object into single object
  System.out.println("Datas of jsons"+json);//values are overriding
}

Upvotes: 2

Related Questions