From map to json java

Serialize /Convert Map of object to/from JSON in java (GSON /example)

Program – convert Map to/from JSON in java(GSON /example)

1.) Person Class:

  • Person class containing firstName, lastName, age etc.
  • We have overloaded toString method to print person information.
package org.learn.gson; public class Person < public String firstName; public String lastName; public int age; public String contact; public Person(String firstName, String lastName, int age, String contact) < this.firstName = firstName; this.lastName = lastName; this.age = age; this.contact = contact; >public String toString() < return "[" + firstName + " " + lastName + " " + age + " " + contact + "]"; >>

2.) JSONMapConverter Class:

JSONMapConverter is responsible for performing following operations.

package org.learn.gson; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class JSONMapConverter < public static void main(String[] args) < Gson objGson = new GsonBuilder().setPrettyPrinting().create(); MapmapIdPerson = new HashMap<>(); mapIdPerson.put("10101001", new Person("Mike", "harvey", 34, "001894536")); mapIdPerson.put("20202002", new Person("Nick", "young", 75, "005425676")); mapIdPerson.put("30303003", new Person("gary", "hudson", 21, "009654153")); mapIdPerson.put("40404004", new Person("gary", "hudson", 55, "00564536")); Type listType = new TypeToken() < >.getType(); String mapToJson = objGson.toJson(mapIdPerson); System.out.println("1. Map to JSON conversion is : \n"); System.out.println(mapToJson); // JSON to Map Map jsonToMap = objGson.fromJson(mapToJson, listType); System.out.println("2. JSON to Map conversion is :\n"); jsonToMap.forEach((k, v) -> System.out.println(k + " text-align: center;">Download Code – Convert Map to JSON Java (GSON /Example) 

Output – convert Map to/from JSON in java (GSON /example)

1. Map to JSON conversion is : < "30303003": < "firstName": "gary", "lastName": "hudson", "age": 21, "contact": "009654153" >, "10101001": < "firstName": "Mike", "lastName": "harvey", "age": 34, "contact": "001894536" >, "20202002": < "firstName": "Nick", "lastName": "young", "age": 75, "contact": "005425676" >, "40404004": < "firstName": "gary", "lastName": "hudson", "age": 55, "contact": "00564536" >> 2. JSON to Map conversion is : 30303003=[gary hudson 21 009654153] 10101001=[Mike harvey 34 001894536] 20202002=[Nick young 75 005425676] 40404004=[gary hudson 55 00564536]

You may also like:

Источник

How to Convert Java Map to JSON

Last updated: 12 November 2019 There are a number of ways to convert a Java Map into JSON. It is quite common to convert Java Arrays and Maps into JSON and vice versa. In this post, we look at 3 different examples to convert Java Map to JSON. We will be using Jackson, Gson and org.json libraries.

Java Map to JSON using Jackson

The following example uses Jackson Core and Jackson Binding to convert Java Map to JSON. In order to use the Jackson libraries, we first need to add them to our pom.xml file:

  com.fasterxml.jackson.core jackson-core 2.9.8  com.fasterxml.jackson.core jackson-databind 2.9.8   
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; public class ConvertJavaMapToJson < @Test public void convertMapToJson() < Mapelements = new HashMap(); elements.put("Key1", "Value1"); elements.put("Key2", "Value2"); elements.put("Key3", "Value3"); ObjectMapper objectMapper = new ObjectMapper(); try < String json = objectMapper.writeValueAsString(elements); System.out.println(json); >catch (JsonProcessingException e) < e.printStackTrace(); >> > 

As can be seen from the output, the order of the elements in the JSON are not the same as the order we added them to the map. To retain the order, we need to use SortedMap instead. e.g.

SortedMap elements = new TreeMap(); 

Java Map to JSON using Gson

The following example uses Gson library to convert Java Map to JSON, but first, we need to add Gson as a dependency to pom.xml file.

  com.google.code.gson gson 2.8.5   
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.junit.jupiter.api.Test; import java.lang.reflect.Type; import java.util.HashMap; import java.util.SortedMap; import java.util.TreeMap; public class ConvertJavaMapToJson < @Test public void convertMapToJson() < SortedMapelements = new TreeMap(); elements.put("Key1", "Value1"); elements.put("Key2", "Value2"); elements.put("Key3", "Value3"); Gson gson = new Gson(); Type gsonType = new TypeToken()<>.getType(); String gsonString = gson.toJson(elements,gsonType); System.out.println(gsonString); > > 

Java Map to JSON using org.json

The following example uses org.json library to convert Java Map to JSON, but first, we need to add org.json as a dependency to pom.xml file.

import org.json.JSONObject; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; public class ConvertJavaMapToJson < @Test public void convertMapToJson() < Mapelements = new HashMap<>(); elements.put("Key1", "Value1"); elements.put("Key2", "Value2"); elements.put("Key3", "Value3"); JSONObject json = new JSONObject(elements); System.out.println(json); > > 

Источник

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.

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

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:

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:

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

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:

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

Other Useful References:

Author

Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks. View all posts

2 Comments

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

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 Reply

Submit a Comment Cancel reply

Subscribe to our Newsletter

About Techndeck

Techndeck.com is a blog revolves around software development & testing technologies. All published posts are simple to understand and provided with relevant & easy to implement examples.

Techndeck.com’s author is Deepak Verma aka DV who is an Automation Architect by profession, lives in Ontario (Canada) with his beautiful wife (Isha) and adorable dog (Fifi). He is crazy about technologies, fitness and traveling etc. He runs a Travel Youtube Channel as well. He created & maintains Techndeck.com

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.

Источник

Convert Map to/from JSON string in java (jackson objectmapper/ example)

Jackson objectMapper maven Dependencies

 com.fasterxml.jackson.core jackson-databind 2.7.1  

Serialize or Convert Map to/from JSON in java (jackson objectmapper)

1.) Person Class:

package org.learn; public class Person < public String firstName; public String lastName; public int age; public Person() < >public Person(String firstName, String lastName, int age) < this.firstName = firstName; this.lastName = lastName; this.age = age; >public String toString() < return "[" + firstName + " " + lastName + " " + age +"]"; >>

2.) JSONMapConverter Class:

package org.learn; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class JSONMapConverter < public static void main( String[] args ) throws IOException < ObjectMapper objectMapper = new ObjectMapper(); //Set pretty printing of json objectMapper.enable(SerializationFeature.INDENT_OUTPUT); //Define map which will be converted to JSON MapmapIdPerson = new HashMap<>(); mapIdPerson.put("10101001", new Person("Mike", "harvey", 34)); mapIdPerson.put("20202002", new Person("Nick", "young", 75)); mapIdPerson.put("30303003", new Person("gary", "hudson", 21)); mapIdPerson.put("40404004", new Person("gary", "hudson", 55)); //1. Convert Map to JSON String mapToJson = objectMapper.writeValueAsString(mapIdPerson); System.out.println("1. Convert Map to JSON :"); System.out.println(mapToJson); //2. JSON to Map //Define Custom Type reference for map type TypeReference> mapType = new TypeReference() <>; Map jsonToMap = objectMapper.readValue(mapToJson, mapType); System.out.println("\n2. Convert JSON to Map :"); //Print map output using Java 8 jsonToMap.forEach((k, v) -> System.out.println(k + " text-align: center;">Download Example Code – Convert Serialize Jackson Map to JSON Java 

Output – Serialize/convert Map to/from JSON in java (jackson objectmapper)

1. Convert Map to JSON : < "30303003" : < "firstName" : "gary", "lastName" : "hudson", "age" : 21 >, "10101001" : < "firstName" : "Mike", "lastName" : "harvey", "age" : 34 >, "20202002" : < "firstName" : "Nick", "lastName" : "young", "age" : 75 >, "40404004" : < "firstName" : "gary", "lastName" : "hudson", "age" : 55 >> 2. Convert JSON to Map : 30303003=[gary hudson 21] 10101001=[Mike harvey 34] 20202002=[Nick young 75] 40404004=[gary hudson 55]

You may also like:

Источник

Читайте также:  Img class name css
Оцените статью