Comment convertir Hashmap en objet JSON en Java

Rupam Yadav 12 octobre 2023
  1. new JSONObject(hashmap) pour convertir le Hashmap en objet JSON
  2. La bibliothèque Jackson convertit le Hashmap en un objet JSON
  3. Bibliothèque GSON pour convertir le Hashmap en objet JSON
Comment convertir Hashmap en objet JSON en Java

Cet article montre comment convertir un hashmap en un objet JSON en Java. Nous verrons en détail les exemples de création d’un hashmap et de sa conversion en objet JSON.

Hashmap et JSON sont tous deux très couramment utilisés par les développeurs car ils nous aident à créer une structure simple qui peut être utilisée pour stocker et transférer des données facilement.

new JSONObject(hashmap) pour convertir le Hashmap en objet JSON

La façon la plus traditionnelle de convertir un hashmap en objet JSON est d’appeler JSONObject() et de passer ensuite le hashmap.

Voyons un exemple qui crée un hashmap et l’imprime ensuite au format JSON.

import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONObject;

public class Main {
  public static void main(String[] args) {
    Map<String, Object> map = new HashMap();

    map.put("key1", "value1");
    map.put("key2", "value2");

    JSONObject json = new JSONObject(map);
    System.out.printf("JSON: %s", json);
  }

Production:

JSON: {"key1":"value1","key2":"value2"}

Une chose à noter ici est que Map<String, Object> prend une chaîne de caractères, qui est la key, et l’Object, qui est la value. Cela signifie que nous pouvons passer n’importe quel objet valide comme valeur dans la carte et le convertir ensuite en objet JSON.

Voici un exemple qui prend une chaîne et une Arraylist comme valeur.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONObject;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> stringArrayList = new ArrayList<>();
    stringArrayList.add("firstString");
    stringArrayList.add("secondString");
    stringArrayList.add("thirdString");

    Map<String, Object> map = new HashMap();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("stringList", stringArrayList);

    JSONObject json = new JSONObject(map);
    System.out.printf("JSON: %s", json);
  }

Production:

JSON: {"key1":"value1","key2":"value2","stringList":["firstString","secondString","thirdString"]}

La bibliothèque Jackson convertit le Hashmap en un objet JSON

Il existe des bibliothèques en Java qui peuvent nous aider à convertir notre hashmap en un objet JSON avec beaucoup de flexibilité.

Jackson est l’une de ces bibliothèques qui prend une map en Java et la convertit ensuite au format JSON.

Nous ne devons pas oublier de gérer l’exception JsonProcessingException car ObjectMapper().writeValueAsString(map) peut lancer une exception lorsqu’il trouve un format de données incompatible.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String[] args) throws JsonProcessingException {
    Map<String, Object> map = new HashMap();
    map.put("key1", "value1");
    map.put("key2", "value2");

    String json = new ObjectMapper().writeValueAsString(map);
    System.out.printf("JSON: %s", json);
  }

Production:

JSON: {"key1":"value1","key2":"value2"}

Bibliothèque GSON pour convertir le Hashmap en objet JSON

La bibliothèque Gson est l’une des bibliothèques les plus utilisées pour convertir un hashmap en un objet JSON. Elle fournit des méthodes faciles pour travailler sur nos hashmap et JSON.

La classe Gson a une méthode toJsonTree, qui prend notre carte et la convertit en un arbre JSON. Mais comme nous avons besoin d’un objet JSON, nous pouvons utiliser toJSONObject() pour faire de l’arbre JSON un objet JSON.

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    Map<String, Object> map = new HashMap();
    map.put("key1", "value1");
    map.put("key2", "value2");

    Gson gson = new Gson();
    JsonObject json = gson.toJsonTree(map).getAsJsonObject();

    System.out.printf("JSON: %s", json);
  }

Production:

JSON: {"key1":"value1","key2":"value2"}
Auteur: Rupam Yadav
Rupam Yadav avatar Rupam Yadav avatar

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

LinkedIn

Article connexe - Java JSON

Article connexe - Java Hashmap