Android中解析json的类库有不少,本文以谷歌的com.google.code.gson:gson库为例,介绍如何在不知道key的情况下,解析如下简单的json字符串。
待解析的json字符串:
{ "key11": "value11", "key12": "value12", "key13": "value13" }
build.gradle
dependencies {
implementation "com.google.code.gson:gson:2.8.6"
}
java代码
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public static HashMap<String, String> readJson(String json) {
HashMap<String, String> jsonMap = new HashMap<>();
if (json != null && !json.isEmpty()) {
try {
Gson gson = new Gson();
Type type = (new TypeToken<Map<String, String>>() {
}).getType();
Map<String, String> tempMap = gson.fromJson(json, type);
Iterator iterator = tempMap.keySet().iterator();
while (iterator.hasNext()) {
Object key = iterator.next();
Object value = tempMap.get(key);
System.out.println("readJson key=" + key + ",value=" + value);
jsonMap.put(key.toString(), value.toString());
}
} catch (Exception x) {
x.printStackTrace();
}
}
return jsonMap;
}
|