Reputation: 1
I am trying to generate key value pair JSON format, but it gets overwritten, Could anyone help me please
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
}
[
{"Des":"Mani","Amount":846},
{"Des":"Shiva","Amount":900},
{"Des":"Sam","Amount":23},
{"Des":"Rajashree","Amount":923},
{"Des":"Kokila","Amount":86},
{"Des":"Samantha","Amount":12}
]
[
{"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
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