json解析(自動判斷是jsonArray和jsonObject)


因為想做一個接口自動化框架,已經實現了接口的訪問和連接及獲取接口返回的json數據,但json數據的解析是個麻煩的事情,所以寫一個簡單的版本記錄一下。后續會進行優化,實現方法分離以及自動識別循環解析返回想要校驗的value

解析json需要導入的包:

json-lib-***.jar

commons-beanutils-***.jar

commons-collections-***.jar

commons-lang-***.jar

commons-logging-***.jar

ezmorph-***.jar

好了,直接上代碼:

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONTokener;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

public class JSONObjectTest {
public static void main(String[] args){
try {
File file = new File("D:\\IdeaProjects\\Solution\\src\\demo.json");
String content = FileUtils.readFileToString(file);
JSONObject obj1 = JSONObject.fromObject(content);
Iterator iterator = obj1.keys();
while(iterator.hasNext()){
String key = (String)iterator.next();
String value = obj1.getString(key);
Object listArray = new JSONTokener(obj1.getString(key)).nextValue();
if(listArray instanceof JSONArray){
JSONArray jsonArray = (JSONArray)listArray;
for(int i=0;i<jsonArray.size();i++){
JSONObject everyParam = jsonArray.getJSONObject(i);
System.out.println(everyParam);
}
}else if(listArray instanceof JSONObject){
JSONObject jsonObject = (JSONObject)listArray;
System.out.println(jsonObject);
}else{
System.out.println(value);
}

}
} catch (IOException e) {
e.printStackTrace();
}

}
}

其中demo.json文件的內容:
{
"age":6,
"name":{"nickname":"xinxin","realname":"www"},
"department":"QA",
"is_student":false,
"hobbies":[
{"dancing":"true"},
{"badminton":"true"}]
}

程序運行打印結果:

6
{"nickname":"xinxin","realname":"www"}
QA
false
{"dancing":"true"}
{"badminton":"true"}

ps:本來直接使用obj1.getString(key),就可以打印json中所有的內容,但我想把是jsonArray的也單獨打印,所以寫了這個,后續完善分離的代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM