0

I have created 3 HashMaps all stored into an Arraylist but I cannot make it into a JSON String, I am using the GSON library.

Any help would kindly be appreciated.

Below you can see all the 3 hashmaps and the ArrayList x am adding them to.

    private void createAdditionalPackages() {

    if (chemoBtn.isChecked()) {
        chemo.put("name", "chemo");
        chemo.put("price", chemoButtonPrice);
    }

    if (cremBtn.isChecked()) {

        cremation.put("name", "crematie");
        cremation.put("price", cremationButtonPrice);
    }

    if (travenBtn.isChecked()) {

        travel.put("name", "reisverz");
        travel.put("price", travelButtonPrice);
    }

    x.add(chemo);
    x.add(cremation);
    x.add(travel);

    List<JsonObject> jsonObjectList = new ArrayList<>() ;
    for(HashMap<String, String> data : x){
        JsonObject object = new JsonObject(data);
        jsonObjectList.add(object);
    }

    JsonArray additional_coverages = new JsonArray(jsonObjectList);

See error :

enter image description here

Black4Guy
  • 641
  • 11
  • 28
AndroidKrayze
  • 349
  • 2
  • 5
  • 21
  • please check this link if you want to convert Arraylist or Hashmap into string via GSON https://stackoverflow.com/questions/37091548/convert-arraylist-with-gson-to-string – Black4Guy Apr 13 '20 at 20:43

2 Answers2

0
    JsonArray additional_coverages = new JsonArray();
    // Iterate over your Hashmap
    for (Map.Entry<String,String> data : x.entrySet()) {
        // Create your JsonObject and use addProperty
        JsonObject object = new JsonObject();
        object.addProperty(data.getKey(), data.getValue());
        // Add data in your JsonArray
        additional_coverages.add(object);
    }
Aman Arora
  • 134
  • 7
0

You cannot directly add list of JsonObject to JsonArray

you can use something like this.

JsonArray additional_coverages = new JsonArray();

for(singleItem in jsonObjectList){
additional_coverages.put(singleItem )
}
suhas sasuke
  • 640
  • 6
  • 7