0
votes

Comment convertir la carte > String dans un objet JSON en Java?

Après avoir récupéré du cache qui est stocké dans un format ci-dessous xxx

je dois le convertir dans un objet JSON. Quelle sera la meilleure façon de le faire?

Objet JSON converti se trouve dans le format ci-dessous xxx


0 commentaires

4 Réponses :


0
votes

Vous pouvez utiliser com.fasterxml.jackson.core Bibliothèque. xxx


0 commentaires

1
votes

Je le ferais avec la bibliothèque Jackson JSON.

ObjectMapper mapper = new ObjectMapper();

Map<String, Map<String, String>> myMap = new HashMap<>();

// add stuff to your map of maps

// pretty print
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(myMap);

System.out.println(json);


0 commentaires

0
votes

Vous pouvez utiliser ObjectMapper CODE> Classe pour activer l'objet de la classe Java dans Jason et Json à Java Class Object

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

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Test {
    public static void main(String[] args) throws JsonProcessingException {
        Map<String, TreeMap<String,String>> m = new HashMap<>();
        TreeMap<String,String> t = new TreeMap<>();
        t.put("address1", "string");
        t.put("address2", "string");
        m.put("address", t);

        ObjectMapper om = new ObjectMapper();
        String json = om.writeValueAsString(m);
        System.out.println(json);
    }
}


0 commentaires

0
votes

GSON est une bonne bibliothèque par Google pour la sérialisation / la désérialisation JSON. Dépendance maven:

Gson gson = new Gson();

Map<String, Map<String, String>> someMap = new HashMap<>();

try (FileWriter writer = new FileWriter("C:\\folder\\file.json")) {
    gson.toJson(someMap, writer);
} catch (IOException e) {
    e.printStackTrace();
}


0 commentaires