使用MultipartFile上传xxx.json文件并解析文件数据


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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM