示例: 将 Map 转为 json string
1.创建 Map 并初始化
Map<String, String> params = new HashMap<>(); params.put("key1", "value1"); params.put("key2", "value2"); params.put("key3", "value3");
2.构建 Gson 对象
Gson gson = new GsonBuilder().create();
3.将 Map 转为 json string
String content = gson.toJson(params); System.out.println(content);
输出:
{“key1”:“value1”,“key2”:“value2”,“key3”:“value3”}
fromJson 将字符串转换为对应的实体类对象
gson.fromJson(json, NotificationBean.class);