In this post we will demonstrate how to convert a map to a JSON array in Java 8 using GSON.
Setup:
You will need to include the following dependancy into your project.
1 2 3 4 5 |
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.3.1</version> </dependency> |
Convert Map to JSON array:
The following example shows how to convert a map to a JSON array. The example uses the stream() method along with map and reduce. It converts each map entry into a JsonObject and then reduces it into a single JsonArray object which contains all the JsonObjects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
@Test public void convertMapToJsonString() { Map<String, String> relationshipStatus = new HashMap<>(); relationshipStatus.put("bob", "married"); relationshipStatus.put("foo", "single"); relationshipStatus.put("bar", "divorced"); relationshipStatus.put("baz", "single"); JsonArray collect = relationshipStatus.entrySet().stream().map(r -> { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("name", r.getKey()); jsonObject.addProperty("relationshipStatus", r.getValue()); return jsonObject; }).reduce(new JsonArray(), (jsonArray, jsonObject) -> { jsonArray.add(jsonObject); return jsonArray; }, (jsonArray, otherJsonArray) -> { jsonArray.addAll(otherJsonArray); return jsonArray; }); Gson gson = new GsonBuilder().setPrettyPrinting().create(); System.out.println("collect = " + gson.toJson(collect)); } |
Output
In running the above code you get the following output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
collect = [ { "name": "bar", "relationshipStatus": "divorced" }, { "name": "bob", "relationshipStatus": "married" }, { "name": "foo", "relationshipStatus": "single" }, { "name": "baz", "relationshipStatus": "single" } ] |
Conclusion:
I hope you found this post of use and it helps you solve your development issues
Similar posts:
- How to parse JSON array into a List
- How to convert Java object into JSON
- Java 8 reduce operation example
- Java 8 Stream map example