今天在工作中遇到要解析json并獲取json里所有指定key的值,再把key的值插入對應的數(shù)據(jù)映射表。于是寫了一個遞歸算法來取值。
1.首先導入alibaba的fastjson,用來解析json。當然也可以用其他的解析包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
2.創(chuàng)建兩個工具類方法,用來判斷傳入的是不是json對象或json數(shù)組
public static boolean isJSONObj(Object json){
return json instanceof JSONObject;
}
public static boolean isJSONArray(Object json){
return json instanceof JSONArray;
}
java中的instanceof也稱為類型比較運算符,因為它將實例與類型進行比較。它返回true或false。
3.建立核心多態(tài)方法
public static void getJSONValue(JSONObject json,String k,List<String> list){
for (Object j:json.keySet()){
if(isJSONObj(json.get(j))){
//是對象
JSONObject j2= JSON.parseObject(json.get(j).toString());
getJSONValue(j2,k,list);
}else if(isJSONArray(json.get(j))){
JSONArray j3=JSON.parseArray(json.get(j).toString());
//是數(shù)組
getJSONValue(j3,k,list);
}else if(j==k){
//是字符串
list.add(json.get(j).toString());
}
}
}
public static void getJSONValue(JSONArray json,String k,List<String> list){
for (Object j:json){
if(isJSONObj(j)){
//是對象
JSONObject j2= JSON.parseObject(j.toString());
getJSONValue(j2,k,list);
}else if(isJSONArray(j)){
//是數(shù)組
JSONArray j3=JSON.parseArray(j.toString());
getJSONValue(j3,k,list);
}
}
}
4.接下來寫一個比較復雜的json,里面有對象嵌套數(shù)組的,數(shù)組嵌套對象的,數(shù)組嵌套數(shù)組的
5.調用方法
try {
File file=new File(demo1.class.getResource("/2.json").getPath());
FileInputStream fileInputStream=new FileInputStream(file);
InputStreamReader inputStreamReader=new InputStreamReader(fileInputStream);
BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
String line="";
StringBuffer json=new StringBuffer();
while ((line=bufferedReader.readLine())!=null){
json.append(line);
}
JSONObject j3=JSON.parseObject(json.toString());
List<String> mid=new ArrayList<>();
getJSONValue(j3,"interfaceId",mid);
System.out.println(mid.toString());
}catch (Exception e){
System.out.println(e.getMessage());
}
6.成功獲取

2.png
demo源碼地址:https://github.com/z573419235/studyDemo
個人博客地址: https://mjava.top