This example show you how to convert a java.util.Map
into JSON
string and back to Map
again.
package org.kodejava.gson;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class MapToJson {
public static void main(String[] args) {
Map<String, String> colours = new HashMap<>();
colours.put("BLACK", "#000000");
colours.put("RED", "#FF0000");
colours.put("GREEN", "#008000");
colours.put("BLUE", "#0000FF");
colours.put("YELLOW", "#FFFF00");
colours.put("WHITE", "#FFFFFF");
// Convert a Map into JSON string.
Gson gson = new Gson();
String json = gson.toJson(colours);
System.out.println("json = " + json);
// Convert JSON string back to Map.
Type type = new TypeToken<Map<String, String>>() {
}.getType();
Map<String, String> map = gson.fromJson(json, type);
for (String key : map.keySet()) {
System.out.println("map.get = " + map.get(key));
}
}
}
Here is the result of the program:
json = {"RED":"#FF0000","WHITE":"#FFFFFF","BLUE":"#0000FF","BLACK":"#000000","YELLOW":"#FFFF00","GREEN":"#008000"}
map.get = #FF0000
map.get = #FFFFFF
map.get = #0000FF
map.get = #000000
map.get = #FFFF00
map.get = #008000
Maven Dependencies
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.11.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Makasih bro infonya kalo boleh yang Jackson nya dunk!