简体   繁体   中英

Convert ArrayList of HashMaps into GSON JsonArray

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?

Try this.

        Type type = new TypeToken<ArrayList<HashMap<String, String>>>(){}.getType();
        JsonElement element = new Gson().toJsonTree(x, type);
        JsonArray jsonArray = element.getAsJsonArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM