Java 讀取json
阿新 • • 發佈:2020-12-24
程式碼:
1 package com.util; 2 import com.alibaba.fastjson.JSON; 3 import com.alibaba.fastjson.JSONArray; 4 import com.alibaba.fastjson.JSONObject; 5 6 7 import java.io.*; 8 public class Josn_load { 9 //讀取json檔案 10 public static String readJsonFile(String fileName) { 11 String jsonStr = "";12 try { 13 File jsonFile = new File(fileName); 14 FileReader fileReader = new FileReader(jsonFile); 15 Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8"); 16 int ch = 0; 17 StringBuffer sb = new StringBuffer();18 while ((ch = reader.read()) != -1) { 19 sb.append((char) ch); 20 } 21 fileReader.close(); 22 reader.close(); 23 jsonStr = sb.toString(); 24 return jsonStr; 25 } catch (IOException e) { 26 e.printStackTrace();27 return null; 28 } 29 } 30 31 public static void main(String[] args) { 32 String path = "E:\\Myeclipse\\WorkPlace_graduate\\基於合同糾紛知識圖譜構建及應用\\WebContent\\data\\data_node.json"; 33 String s = readJsonFile(path); 34 JSONObject jobj = JSON.parseObject(s); 35 JSONArray Nodes = jobj.getJSONArray("Nodes");//構建JSONArray陣列 36 for (int i = 0 ; i < Nodes.size();i++){ 37 JSONObject key = (JSONObject)Nodes.get(i); 38 String symbolSize = (String)key.get("name"); 39 System.out.println(key.get("symbolSize")); 40 System.out.println(symbolSize); 41 } 42 } 43 }
JSON: