Convert Map to String Java

Convert Map to String Java | The map is an interface where the data is stored in the form of keys and values. And the keys should be unique. The operation that is inserted, search, delete e.t.c is done on the basis of the key. This interface is present in java.util package. The string is a collection of a sequence of characters. In this section, we will convert the map to a string.

Whenever we print/display the map then, it calls the toString() method on the map object, which converts the map to a string. But to convert the map to string JSON we need external APIs. We will see them through examples.

Java Program to Convert Map to String Java

import java.util.HashMap;

public class Main {
   public static void main(String[] args) {
      HashMap<String, Integer> map = new HashMap<>();
      map.put("apple", 10);
      map.put("strawberries", 50);
      map.put("banana", 20);
      map.put("watermelon", 70);
      map.put("pomegranate", 20);
      map.put("mango", 40);
      System.out.println("Map.toString(): " + map.toString());
      System.out.println("Map: " + map);
   }
}

Output:-

Map.toString(): {banana=20, apple=10, pomegranate=20, strawberries=50, watermelon=70, mango=40}
Map: {banana=20, apple=10, pomegranate=20, strawberries=50, watermelon=70, mango=40}

In JSON viewer this result will be displayed as follows:-

{
  banana=20,
  apple=10,
  pomegranate=20,
  strawberries=50,
  watermelon=70,
  mango=40
}

Let us see a similar example by using objects. We will have Student & Address objects. The Student object will contain id, name & address, and the Address object will contain the city and Pincode. The map will have the student object as the value.

Java Convert Map to String for Objects

public class Student {
   
   private int id;
   
   private String name;
   
   private Address address;

   // setter & getters

   @Override
   public String toString() {
      return "Student [id=" + id + 
            ", name=" + name + 
            ", address=" + address + "]";
   }
}
public class Address {

   private String city;

   private int pincode;

   // setter & getters

   @Override
   public String toString() {
      return "Address [city=" + city + 
            ", pincode=" + pincode + "]";
   }
}

In the Student and Address class, we have to override the toString() method else the map will display only the reference of the Students, not its data or value. The way we define the toString() method will be used to display the map data while conversion.

import java.util.HashMap;

public class Main {
   public static void main(String[] args) {

      Student student1 = new Student();
      student1.setId(101);
      student1.setName("John");
      Address address1 = new Address();
      address1.setCity("Texas");
      address1.setPincode(77449);
      student1.setAddress(address1);

      Student student2 = new Student();
      student2.setId(102);
      student2.setName("William");
      Address address2 = new Address();
      address2.setCity("New York");
      address2.setPincode(11368);
      student2.setAddress(address2);

      HashMap<String, Object> map = new HashMap<>();
      map.put("student1", student1);
      map.put("student2", student2);
      System.out.println("Map: " + map);
   }
}

Output:-

Map: {student2=Student [id=102, name=William, address=Address [city=New York, pincode=11368]], student1=Student [id=101, name=John, address=Address [city=Texas, pincode=77449] ] }

In JSON viewer it displays as below:-

{
  student2=Student[
    id=102,
    name=William,
    address=Address[
      city=NewYork,
      pincode=11368
    ]
  ],
  student1=Student[
    id=101,
    name=John,
    address=Address[
      city=Texas,
      pincode=77449
    ]
  ]
}

Convert Map to JSON String in Java

Example to convert the map to JSON string:-
Map: {banana=2, apple=1, pomegranate=3, mango=4}
String: {“banana”:2,”apple”:1,”pomegranate”:3,”mango”:4}

When we see this JSON string with format/beautify then it will display as,

{
  "banana": 2,
  "apple": 1,
  "pomegranate": 3,
  "mango": 4
}

In the Convert String to Map in Java, we have discussed how to convert string to map using Jackson API. Now, we will see how to convert the map to string JSON using Jackson API. For this, we will need the following dependencies:- Jackson-coreJackson-databind & Jackson-annotations.

import java.util.HashMap;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
   public static void main(String[] args) 
                 throws JsonProcessingException {
      HashMap<String, Integer> map = new HashMap<>();
      map.put("apple", 10);
      map.put("strawberries", 50);
      map.put("banana", 20);
      map.put("watermelon", 70);
      map.put("pomegranate", 20);
      map.put("mango", 40);
      System.out.println("Map: " + map);

      String string = mapToString(map);
      System.out.println("String: " + string);
   }

   public static String mapToString(HashMap<String, Integer> map) 
         throws JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.writeValueAsString(map);
   }
}

Output:-

Map: {banana=20, apple=10, pomegranate=20, strawberries=50, watermelon=70, mango=40}
String: {“banana”:20,”apple”:10,”pomegranate”:20,”strawberries”:50,”watermelon”:70,”mango”:40}

This JSON string will be displayed as follows:-

{
  "banana": 20,
  "apple": 10,
  "pomegranate": 20,
  "strawberries": 50,
  "watermelon": 70,
  "mango": 40
}

Now, let us see another program where for HashMap<String, Object>. Here map will contain string as key and Object as value. The interesting point is:- while using Jackson API to convert the map to the string we don’t need to override the toString() method in the Object class explicitly. Let us see it through an example:-

Java Convert Map to String JSON for Objects

public class Student {
   
   private int id;
   
   private String name;
   
   private Address address;

   // setter & getters
   // toString() not needed
}
public class Address {

   private String city;

   private int pincode;

   // setter & getters
   // toString() not needed
}
import java.util.HashMap;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
   public static void main(String[] args) 
         throws JsonProcessingException {

      Student student1 = new Student();
      student1.setId(101);
      student1.setName("John");
      Address address1 = new Address();
      address1.setCity("Texas");
      address1.setPincode(77449);
      student1.setAddress(address1);

      Student student2 = new Student();
      student2.setId(102);
      student2.setName("William");
      Address address2 = new Address();
      address2.setCity("New York");
      address2.setPincode(11368);
      student2.setAddress(address2);

      HashMap<String, Object> map = new HashMap<>();
      map.put("student1", student1);
      map.put("student2", student2);
      System.out.println("Map: " + map);

      String string = mapToString(map);
      System.out.println("String: " + string);
   }

   public static String mapToString(HashMap<String, Object> map) 
         throws JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.writeValueAsString(map);
   }
}

Output:-

Map: {[email protected], [email protected]}
String: {“student2”:{“id”:102,”name”:”William”,”address”:{“city”:”New York”,”pincode”:11368}},”student1″:{“id”:101,”name”:”John”,”address”:{“city”:”Texas”,”pincode”:77449}}}

The resultant string data will be displayed as follows in JSON beautifier:-

{
  "student2": {
    "id": 102,
    "name": "William",
    "address": {
      "city": "New York",
      "pincode": 11368
    }
  },
  "student1": {
    "id": 101,
    "name": "John",
    "address": {
      "city": "Texas",
      "pincode": 77449
    }
  }
}

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.