Reputation: 605
I have an implementation where when user click on checkbox , a json gets associated as value of checkbox and that value is passed to my bean class. And In the method invoked, the String is then parsed into JSON object. When I select two checkbox, it works perfectly fine. But if I select one checkbox, then it gives me error.
Here is my Checkbox Bean class -
private ArrayList<String> Ancillary=new ArrayList<String>() ;
public ArrayList<String> getAncillary() {
for(int i=0;i<Ancillary.size();i++){
System.out.println(i+"Object:" +Ancillary.get(i)+"\n\n\n");
}
return Ancillary;
}
public void setAncillary(ArrayList<String> ancillary) {
Ancillary = ancillary;
}
Here is my method where I print value of a Particular key in JSON.
public Event updatePax(RequestContext context) throws Exception {
ExtrasMenu extrasMenu = (ExtrasMenu) context.getConversationScope().get(ScopeKeys.EXTRASMENU);
System.out.println("As a string:"+extrasMenu.getAncillary().toString());
JSONObject json=new JSONObject(extrasMenu.getAncillary().get(0));
System.out.println(json.get("firstName"));
}
And here is the Output-
If only one checkbox is selected -
0Object:{"firstName":"TIMOTHY"
1Object:"lastName":"WALKER"
2Object:"price":100}
If two or more checkboxes are selected -
0Object:{"firstName":"TIMOTHY","lastname":"WALKER","price":"50"}
1Object:{"firstName":"ANNE","lastname":"WALKER","price":"150"}
Upvotes: 0
Views: 151
Reputation: 605
Since, I couldnt figure out why ArrayList is taking input like this, I created a special case when User selects one check box. I will take the ArrayList and convert it to a String using toString. So, the output of toString will be like -
{"firstName":"TIMOTHY","lastname":"WALKER","price":"50"}
Now I used a try catch block to create JSON object out of the string I get from toString.
JSONObject json=null;
try{
json=new JSONObject(extrasMenu.getAncillary().get(i));
}
catch(org.json.JSONException e){
int len=extrasMenu.getAncillary().toString().length();
json=new JSONObject(extrasMenu.getAncillary().toString());
}
So If it throws an error, the full list as a string will be used to create JSON object. Although It is working fine, Still I am not very sure about Why ArrayList is working like this !
Upvotes: 1