[JAVA]Json檔案內容有誤出現JSONObject text must begin with ‘{‘ at 1 [character 2 line 1]解決
4 min readSep 4, 2020
step1先將檔案連結丟往json-generator.com
先將有問題的JSON丟入
Step2下載正確的JSON
Step3 JSON匯入使用 JAVAI/O read Json檔案
File file=new File("C:\\Users\\User\\eclipse-workspace\\Lab\\src\\lib\\generated.json");//讀取檔案位置BufferedReader reader = new BufferedReader(new java.io.FileReader(file));//使用BuffereReader 加入讀取String data;StringBuffer jsonBuffer=new StringBuffer();while ((data = reader.readLine()) != null) //讀取json檔{jsonBuffer.append(data); //將讀取到的資料存入jsonBuffer}
Step4 解析Json檔案
先觀察檔案格式
我們需要的資料是Info 當中的 資料 要取得前先一步一步進入
最外層為object XML_Head
接著是 object Infos
最後是JSONArray Info <我們需要的 JSONArray
再透過迴圈取得內部的值
程式碼
JSONObject j = new JSONObject(jsonBuffer.toString());JSONObject jsonOb = j.getJSONObject("XML_Head");JSONObject infos = jsonOb.getJSONObject("Infos");JSONArray info=infos.getJSONArray("Info");for (int i = 0; i < info.length(); i++){String Name = info.getJSONObject(i).getString("Name");System.out.println(Name);}
執行結果
解析可以參考上篇