How to Convert Java Map to JSON

In this post, we will learn how to convert Java Map into a JSON using 3 different libraries. As stated, we are going to use Gson, Jackson, and org.json libraries to achieve our objective one at a time. All three are quite famous libraries and used quite often.

Convert Java Map to JSON...!!! Click To Tweet

In this tutorial, we are going to cover the below topics:

  1. Map to JSON using Gson
  2. Map to JSON using Jackson
  3. Map to JSON using org.json

 

Let’s begin:

1. Convert Java Map to JSON using Gson

In order to work with Gson, we first need to add it’s dependency into the Project. 

Maven dependencies

If you are using Maven as a build tool in your project, then add the following dependency in your pom.xml file.

else, access the below link and download & add the jar into your project classpath:

Gson Jar

Output:

 

2. Convert Java Map to JSON using Jackson

In order to work with Jackson, we first need to add it’s dependency into the Project. 

Maven dependencies

If you are using Maven as a build tool in your project, then add the following dependency in your pom.xml file.

else, download & add the following Jars into your project classpath:

  • jackson-core
  • jackson-databind

In order to download jars, access below link and search for above-mentioned jar names and download the appropriate one from the search result.

Jackson Jar

Output:

3. Convert Java Map to JSON using org.json

In order to work with org.json, we first need to add it’s dependency into the Project. 

Maven dependencies

If you are using Maven as a build tool in your project, then add the following dependency in your pom.xml file.

else, access the below link, it will download the jar in a zip file, extract it and & add this jar into your project classpath:

org.json Jar

Output:

Convert Java Map to JSON...!!! Click To Tweet

Do you like this Post? – then check my other helpful posts:

Other Useful References:

2 thoughts on “How to Convert Java Map to JSON

  1. In section 2. Convert Java Map to JSON using Jackson, you are still using GSON code snippet instead of Jackson, wrong copy-paste?

    1. Hi Serguei,

      Sorry for the inconvenience and thanks for pointing that out. Yes, that was the copy-paste issue. Well, I’ve fixed it now. Please take a look.

      Thanks

Leave a Reply

Your email address will not be published.Required fields are marked *

Facebook Twitter Instagram YouTube