Google的gson包
作者:互联网
感觉在java中处理json蛮好用的一个工具类
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class JSONTest {
@Test
void test() throws FileNotFoundException {
JsonParser parser = new JsonParser();
String filepath = "C:\\Users\\kun\\Desktop\\category";
File file = new File(filepath);
File[] fileList = file.listFiles();
if (fileList != null) {
for (int i = 0; i < fileList.length; i++) {
File value = fileList[i];
JsonObject obj = (JsonObject) parser.parse(new FileReader(value));
JsonArray array = obj.get("data").getAsJsonArray();
JsonElement categoryId = null;
JsonElement categoryName = null;
JsonObject childObj = null;
for (int j = 0; j < array.size(); j++) {
JsonObject subObject = array.get(j).getAsJsonObject();
//资料
// System.out.println(subObject.get("title_name").getAsString());
// String categoryIds = subObject.get("category_ids").getAsString();
// System.out.println(categoryIds.substring(1, categoryIds.length() - 1));
//类别
categoryId = subObject.get("Id");
categoryName = subObject.get("CategoryName");
JsonArray childArray = subObject.get("SonCategoryList").getAsJsonArray();
if (childArray.isEmpty()) {
System.out.println(categoryId + " : " + categoryName);
}
if (!childArray.isEmpty()) {
childObj = new JsonObject();
for (int k = 0; k < childArray.size(); k++) {
JsonObject categoryObj = childArray.get(k).getAsJsonObject();
String id = categoryObj.get("Id").getAsString();
JsonElement name = categoryObj.get("CategoryName");
childObj.add(id, name);
}
System.out.println(categoryId + " : " + categoryName + " ----> " + childObj.toString());
}
}
}
}
}
}
抓包获取了许多网页和wx小程序的json数据 ,使用此类扫描文件目录下的所有json文件,获取对应的kv,打印出来需要的数据。
标签:Google,get,JsonObject,import,subObject,gson,childArray 来源: https://www.cnblogs.com/leejk/p/16385328.html