I would like to create a Json structure manually using JsonObject and JsonArrays like the below:
{
"data":[
{
"company_name":"xyz",
"Amount":"$2000",
"Duplicate_amount":"$500"
},
{
"company_name":"abc",
"Amount":"$5000"
},
{
"company_name":"zzz",
"Amount":"$2500",
"Duplicate_amount":"$1000"
}
]
}
The Json above is to be generated based on a checking done on an Arraylist. For example: Arraylist [xyz,abc,zzz,xyz,hhh,zzz]. Now I want to check, if the arraylist contains duplicate elements i.e here "xyz" and "zzz" then in the Json structure, the Duplicate_amount Json object to be added in the Json. Else if no duplicate present then only "company_name" and "amount" to be formed. The whole json format to be formed in this way.
How to do it? I have the logic for finding duplicate elements. But I cannot seem to find the logic for forming the above json based on the checking.
Thank you
Updates
So far I have tried this with checking. But the below code doesn't work and is not forming the appropriate json. What is the solution ?:
JSONObject root_jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
JSONObject sub_jsonobj= new JSONObject();
Object[] st = AppData.customer_arr.toArray();
for (Object s : st) {
//The if-else is the duplicate checking part here
if (AppData.customer_arr.indexOf(s) != AppData.customer_arr.lastIndexOf(s)) {
try {
sub_jsonobj.put("name",AppData.customer_arr.get(counter));
sub_jsonobj.put("dup_amount",AppData.amt_arr.get(counter));
} catch (Exception e) {
e.printStackTrace();
}
}
else{
try {
sub_jsonobj.put("name",AppData.customer_arr.get(counter));
sub_jsonobj.put("amount",AppData.amt_arr.get(counter));
} catch (Exception e) {
e.printStackTrace();
}
}
jsonArr.put(sub_jsonobj);
counter++;
}
try {
root_jsonObj.put("data", jsonArr);
} catch (Exception e) {
e.printStackTrace();
}