Après avoir récupéré du cache qui est stocké dans un format ci-dessous je dois le convertir dans un objet JSON. Quelle sera la meilleure façon de le faire? P> Objet JSON converti se trouve dans le format ci-dessous p>
4 Réponses :
Vous pouvez utiliser com.fasterxml.jackson.core Bibliothèque.
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);
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);
}
}
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(); }