给予一个可以转为list的未知层数的json字符串写一个取最底下一层list的数据的方法用java
可以使用递归的方式来实现。具体步骤如下:
- 将json字符串转为JsonObject对象。
- 判断JsonObject是否包含"list"字段,如果包含则继续递归,否则返回当前JsonObject对象。
- 如果包含"list"字段,则获取"list"字段对应的JsonArray对象。
- 遍历JsonArray对象,将每个元素转为JsonObject对象,再递归调用当前方法。
- 将递归得到的结果添加到一个List中,并返回该List。
代码如下:
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
public class JsonUtil {
public static List<JsonObject> getBottomList(String json) {
List<JsonObject> result = new ArrayList<>();
Gson gson = new Gson();
JsonElement element = gson.fromJson(json, JsonElement.class);
if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
if (obj.has("list")) {
JsonArray array = obj.getAsJsonArray("list");
for (JsonElement e : array) {
if (e.isJsonObject()) {
result.addAll(getBottomList(e.getAsJsonObject().toString()));
}
}
} else {
result.add(obj);
}
}
return result;
}
}
使用示例:
String json = "{\n" +
" \"name\": \"root\",\n" +
" \"list\": [\n" +
" {\n" +
" \"name\": \"level1-1\",\n" +
" \"list\": [\n" +
" {\n" +
" \"name\": \"level2-1\",\n" +
" \"list\": [\n" +
" {\n" +
" \"name\": \"bottom1\",\n" +
" \"value\": 100\n" +
" },\n" +
" {\n" +
" \"name\": \"bottom2\",\n" +
" \"value\": 200\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"name\": \"level2-2\",\n" +
" \"list\": [\n" +
" {\n" +
" \"name\": \"bottom3\",\n" +
" \"value\": 300\n" +
" },\n" +
" {\n" +
" \"name\": \"bottom4\",\n" +
" \"value\": 400\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"name\": \"level1-2\",\n" +
" \"list\": [\n" +
" {\n" +
" \"name\": \"level2-3\",\n" +
" \"list\": [\n" +
" {\n" +
" \"name\": \"bottom5\",\n" +
" \"value\": 500\n" +
" },\n" +
" {\n" +
" \"name\": \"bottom6\",\n" +
" \"value\": 600\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"name\": \"level2-4\",\n" +
" \"list\": [\n" +
" {\n" +
" \"name\": \"bottom7\",\n" +
" \"value\": 700\n" +
" },\n" +
" {\n" +
" \"name\": \"bottom8\",\n" +
" \"value\": 800\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}";
List<JsonObject> bottomList = JsonUtil.getBottomList(json);
for (JsonObject obj : bottomList) {
System.out.println(obj.toString());
}
输出如下:
{"name":"bottom1","value":100}
{"name":"bottom2","value":200}
{"name":"bottom3","value":300}
{"name":"bottom4","value":400}
{"name":"bottom5","value":500}
{"name":"bottom6","value":600}
{"name":"bottom7","value":700}
{"name":"bottom8","value":800}
原文地址: https://www.cveoy.top/t/topic/br0N 著作权归作者所有。请勿转载和采集!