標籤:
一、首先需要在Eclipse工程中匯入相關的jar包,jar包參見連結:http://yunpan.alibaba-inc.com/share/link/NdA5b6IFK
二、
提供一份待解析的json檔案,apkinfo.json如下:[{"name":"帳號","package_name":"com.android.account","check_version":"1.2"},{"name":"系統升級","package_name":"com.android.osupdate","check_version":"1.0"},]三、
Java代碼由兩個類組成,一個是讀取檔案內容的Util類,還有一個是主程式Test類。(1)
Util.java:import java.io.BufferedReader;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader; public class Util { public String ReadFile(String Path){BufferedReader reader = null;String laststr = "";try{FileInputStream fileInputStream = new FileInputStream(Path);InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");reader = new BufferedReader(inputStreamReader);String tempString = null;while((tempString = reader.readLine()) != null){laststr += tempString;}reader.close();}catch(IOException e){e.printStackTrace();}finally{if(reader != null){try {reader.close();} catch (IOException e) {e.printStackTrace();}}}return laststr;} }(2)
Test.java:import java.util.ArrayList;import java.util.Iterator;import java.util.List; import net.sf.json.JSONArray;import net.sf.json.JSONObject; public class Test { public static void main(String[] args) {// TODO Auto-generated method stubString JsonContext = new Util().ReadFile("D:\\test\\apkinfo.json");JSONArray jsonArray = JSONArray.fromObject(JsonContext);int size = jsonArray.size();System.out.println("Size: " + size);for(int i = 0; i < size; i++){JSONObject jsonObject = jsonArray.getJSONObject(i);System.out.println("[" + i + "]name=" + jsonObject.get("name"));System.out.println("[" + i + "]package_name=" + jsonObject.get("package_name"));System.out.println("[" + i + "]check_version=" + jsonObject.get("check_version"));}} }
四、執行後的結果如下:Size: 2[0]name=帳號[0]package_name=com.android.account[0]check_version=1.2[1]name=系統升級[1]package_name=com.android.osupdate[1]check_version=1.0
Java解析JSON檔案的方法(一)