Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonObject add property - maps

Tags:

java

json

gson

I have a class called Test with a String id field and a HashMap map like Map<String, String[]>, Map<String, ArrayList<String>>, and Map<String, HashMap> (Here the second HashMap is a <String, Integer> one) I have the following code.

JsonObject jsonObject = new JsonObject();

jsonObject.addProperty("id", test.getId);

Like this, I want to add the Map to this. Adding like jsonObject.addProperty("map", String.valueOf(test.getMap())); does not do the work properly as it add "(commas) to beginning and end. Can somebody tell me what is the correct way to do it?

like image 970
harsh Avatar asked Jan 23 '26 12:01

harsh


1 Answers

JsonObject has add method to add primitives, but only a single add method to add complex types. This method expects a JsonElement so that's what you have to create.

JsonObject jsonObject = new JsonObject();
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(test.getMap());
jsonObject.add("map", jsonElement);

I don't know exactly why you're doing this. In your last question, I showed you how to generate full JSON from the Test class.

You can use

gson.toJsonTree(test);

to get the JSON as a JsonElement, which you can cast to a JsonObject.

like image 170
Sotirios Delimanolis Avatar answered Jan 25 '26 00:01

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!