0

I Am trying to convert the following Arraylist of HashMaps into a JsonArray so I can add it to my JsonObject.

I have created three hashmaps that contain a value pair and then each is added to an ArrayList which has to be converted to a JsonArray so it can be accepted into the GSON JsonObject.

I tried converting it into a String which did not give me the prefered output. Also tried converting that String back to a JsonArray without any luck.

     HashMap<String, String> chemo = new HashMap<>();
     HashMap<String, String> cremation = new HashMap<>();
     HashMap<String, String> travel = new HashMap<>();

     ArrayList<HashMap<String, String>> x = new ArrayList<>();

        private void createAdditionalPackages() {

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

        }

        if (cremBtn.isChecked()) {

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

        }

        if (travenBtn.isChecked()) {

            travel.put("name", "reisverz");
            travel.put("price", travelButtonPrice);
            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);

        // Toast.makeText(this, additional_coverages.toString(), Toast.LENGTH_SHORT).show();

        String json = new Gson().toJson(x);



        Intent submitUserInformation = new Intent(PetplanAdditionalPlansActivity.this, 
 AnimalInsuranceActivityUserInfo.class);
        submitUserInformation.putExtra("coverages", json);
            submitUserInformation.putExtra("animal_age", animalAge);
            submitUserInformation.putExtra("additional_coverages", x);
            startActivity(submitUserInformation);
        }

Any ideas?

1 Answer 1

0

Try this.

        Type type = new TypeToken<ArrayList<HashMap<String, String>>>(){}.getType();
        JsonElement element = new Gson().toJsonTree(x, type);
        JsonArray jsonArray = element.getAsJsonArray();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.