android json转map
时间: 2023-09-13 08:07:47 浏览: 29
你可以使用以下代码将 JSON 字符串转换为 Map 对象:
```java
public static Map<String, Object> jsonToMap(String json) throws JSONException {
Map<String, Object> map = new HashMap<>();
JSONObject jsonObject = new JSONObject(json);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
Object value = jsonObject.get(key);
if (value instanceof JSONArray) {
value = jsonToList((JSONArray) value);
} else if (value instanceof JSONObject) {
value = jsonToMap(value.toString());
}
map.put(key, value);
}
return map;
}
public static List<Object> jsonToList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if (value instanceof JSONArray) {
value = jsonToList((JSONArray) value);
} else if (value instanceof JSONObject) {
value = jsonToMap(value.toString());
}
list.add(value);
}
return list;
}
```
使用示例:
```java
String jsonStr = "{\"name\":\"John\",\"age\":30,\"cars\":[\"Ford\",\"BMW\",\"Fiat\"]}";
Map<String, Object> map = jsonToMap(jsonStr);
System.out.println(map.get("name")); // John
System.out.println(map.get("age")); // 30
System.out.println(map.get("cars")); // [Ford, BMW, Fiat]
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)