1.Controller 接 收 到 json文件:
public String uploadNproductJsonFile(@RequestParam("file") MultipartFile json_file) {
String jsonName=json_file.getOriginalFilename(); //獲取JSON類型的文件名
ReadUtils rea= new ReadUtils();
String JsonContext=rea.ReadFile(jsonName); //輸出的數據是{}花括號包裹的
String JsonContextArr="["+JsonContext+"]"; //因為JSONArray.parseArray是將 "[ ]"包裹的數據轉化為數組,所以在這里先用“[]”拼接
JSONArray jsonArray =JSONArray.parseArray(JsonContextArr); //JSON數據轉化為數組
int size = jsonArray.size();
for(int i = 0; i < size; i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String VID=(String) jsonObject.get("identity"); //獲取里面的數據
}
return "SUCCESS";
}
2.創建一個Utile,用於讀取json文件:
public String ReadFile(String Path){
BufferedReader reader = null; //BufferedReader:入參有Reader對象和緩沖區大小(可不寫)從緩沖區讀取字符流,提高效率;緩沖區大小:默認8192,默認不需要傳遞建議都要用這個類去讀取文件
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){ //BufferedReader對象使用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;
}
初次了解來源於:https://www.cnblogs.com/lucky-star-star/p/4348450.html