Java如何将Map转换为JSON?
此示例演示如何转换java.util.Map文件转换为JSON字符串并再次返回映射。
package org.nhooo.example.google.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");
// 将映射转换为JSON字符串。
Gson gson = new Gson();
String json = gson.toJson(colours);
System.out.println("json = " + json);
// 将JSON字符串转换回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));
}
}
}
这是程序的结果:
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依赖
<!-- http://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.0/gson-2.8.0.jar --><dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
以上是 Java如何将Map转换为JSON? 的全部内容, 来源链接: utcz.com/z/340719.html