coding made simple with some delicious cake

Java 8 – Convert Map to JSON Array

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.

Maven Dependency

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.

Example

Java

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

publicvoidconvertMapToJsonString(){

Map<String,String>relationshipStatus=newHashMap<>();

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=newJsonObject();

jsonObject.addProperty("name",r.getKey());

jsonObject.addProperty("relationshipStatus",r.getValue());

returnjsonObject;

}).reduce(newJsonArray(),(jsonArray,jsonObject)->{

jsonArray.add(jsonObject);

returnjsonArray;

},(jsonArray,otherJsonArray)->{

jsonArray.addAll(otherJsonArray);

returnjsonArray;

});

Gson gson=newGsonBuilder().setPrettyPrinting().create();

System.out.println("collect = "+gson.toJson(collect));

}

Output

In running the above code you get the following output

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