使用gson怎么把HashMap对象转为json格式,再从json字符串转回HashMap
时间: 2024-02-09 08:35:50 浏览: 139
使用Google的Gson实现对象和json字符串之间的转换
1. 将HashMap对象转为json格式:
```java
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("key1", "value1");
hashMap.put("key2", "value2");
Gson gson = new Gson();
String json = gson.toJson(hashMap);
System.out.println(json); // {"key1":"value1","key2":"value2"}
```
2. 将json字符串转回HashMap对象:
```java
String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
Type type = new TypeToken<HashMap<String, String>>(){}.getType();
HashMap<String, String> hashMap = new Gson().fromJson(json, type);
System.out.println(hashMap); // {key1=value1, key2=value2}
```
阅读全文