android上json转map的代码
时间: 2023-02-25 07:04:03 浏览: 71
在 Android 中使用 Gson 库可以很方便地实现 JSON 字符串转成 Map。首先需要添加 Gson 库的依赖,例如:
```
implementation 'com.google.code.gson:gson:2.8.6'
```
然后在代码中使用如下代码:
```
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
// ...
Gson gson = new Gson();
String json = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
// JSON字符串转成Map
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> map = gson.fromJson(json, type);
// 访问Map中的数据
String name = (String) map.get("name");
Integer age = (Integer) map.get("age");
String city = (String) map.get("city");
System.out.println(name);
System.out.println(age);
System.out.println(city);
```
Gson 库提供了强大的 JSON 解析功能,除了上面的示例代码,还可以方便地将 JSON 字符串解析成其他 Java 对象。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)