Java解析JSON檔案的方法(一)

來源:互聯網
上載者:User

標籤:

一、首先需要在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檔案的方法(一)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.