美文网首页vue2.x
读取json文件

读取json文件

作者: WebGiser | 来源:发表于2018-07-03 15:33 被阅读25次

    需求:用户在页面上选择本地json文件后,进行解析和展示。
    解决方案;1、利用js直接对json文件进行解析。2、ajax把文件传送到服务器,利用java解析json文件,然后返回数据。

    hospital.json文件示例

    {
        "hospital":[
            {
                "lon":120,
                "lat":30,
                "name":"西安医院"
            },
            {
                "lon":130,
                "lat":40,
                "name":"北京医院"
            }
        ]
    }
    

    html代码

    <input type="file" id="poiFile"/>
    <button id = "importFile" >导入</button>
    

    1、js解析json文件

    <script type="text/javascript" src="./jquery3.3.1.js"></script>
    <script type="text/javascript">
              $(function(){
                    $("#importFile").click(function(){
                        //获取文件列表
                        var files = $('#poiFile').prop('files');
                        console.log(files);
    
                        if(files.length == 0){
                            alert("请先选择json文件");
                            return;
                        }
    
                        //获取文件名称
                        var fileName = files[0].name.substring(0,files[0].name.lastIndexOf("."));
    
                        if(files.length == 0){
                            alert('请选择文件');
                            return;
                        }else{
                            //新建一个FileReader
                            var reader = new FileReader();
                            //读取文件
                            reader.readAsText(files[0], "UTF-8"); 
                            //读取完文件之后的回调函数
                            reader.onload = function(evt){ 
                                var fileString = evt.target.result;
                                var fileJson = JSON.parse(fileString);
                                $.each(fileJson["键"], function(i, item) {
                                          alert(item.lon+","+item.lat);     
                                 })
                            }
                        }
                    })
                })
    </script>
    

    2、ajax上传文件,java解析

    2.1 ajax代码

    <script type="text/javascript" src="./jquery3.3.1.js"></script>
    <script type="text/javascript">
    $(function(){
                $("#importFile").click(function(){
                        if($("#poiFile")[0].files.length == 0){
                            alert("请先选择json文件");
                            return;
                        }
                        var formData = new FormData();
                        formData.append("myfile", $("#poiFile")[0].files[0]);   
                        $.ajax({
                            url: "http://127.0.0.1:8080/filetemp/file/upload",
                            type: "post",
                            data: formData,
                            //必须false才会自动加上正确的Content-Type
                            contentType: false,
                            //必须false才会避开jQuery对 formdata 的默认处理
                            //XMLHttpRequest会对 formdata 进行正确的处理
                            processData: false,
                            success: function (datas) {
                                console.log(datas);
                                var data = JSON.parse(datas);
                                $.each(data["键"], function(i, item) {
                                    alert(item.lon+","+item.lat);
                            },
                            error: function () {
                                alert("上传失败!");
                            }
                        });
                    })
                }) 
    </script>
    

    2.2 springMVC框架搭建

    image.png

    pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    
      <modelVersion>4.0.0</modelVersion>
      <packaging>war</packaging>
    
      <name>filetemp</name>
      <groupId>FileTemp</groupId>
      <artifactId>filetemp</artifactId>
      <version>1.0-SNAPSHOT</version>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
          </plugin>
        </plugins>
      </build>
    
      <dependencies>
        <!--Spring依赖-->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>5.0.0.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>5.0.0.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
          <version>5.0.0.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>5.0.0.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>5.0.0.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>5.0.0.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>5.0.0.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>5.0.0.RELEASE</version>
        </dependency>
    
        <!--fileupload文件下载-->
        <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.2</version>
        </dependency>
    
        <dependency>
          <groupId>org.json</groupId>
          <artifactId>json</artifactId>
          <version>20180130</version>
        </dependency>
      </dependencies>
    
    </project>
    

    spring-mvc.xml代码

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                                http://www.springframework.org/schema/beans/spring-beans.xsd
                                http://www.springframework.org/schema/context
                                http://www.springframework.org/schema/context/spring-context.xsd
                                http://www.springframework.org/schema/mvc
                                http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!-- mvc的注解驱动 -->
        <mvc:annotation-driven/>
    
        <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
        <context:component-scan base-package="controller" />
    
        <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 默认编码 -->
            <property name="defaultEncoding" value="utf-8" />
            <!-- 文件最大值 -->
            <property name="maxUploadSize" value="10485760000" />
            <!-- 内存中的最大值 -->
            <property name="maxInMemorySize" value="40960" />
        </bean>
    </beans>
    

    web.xml代码

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4"
             xmlns="http://java.sun.com/xml/ns/j2ee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                                http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    
        <!-- 编码过滤器 -->
        <filter>
            <filter-name>encodingFilter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>encodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/spring-mvc.xml</param-value>
        </context-param>
    
        <!-- Spring MVC servlet -->
        <servlet>
            <servlet-name>SpringMVC</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:config/spring-mvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>SpringMVC</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <!-- Spring监听器 -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <!-- 防止Spring内存溢出监听器 -->
        <listener>
            <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
        </listener>
    
    
        <welcome-file-list>
            <welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
        </welcome-file-list>
    
    </web-app>     
    

    2.3 java解析文件代码

    FileUploadController.java代码

    package controller;
    
    import org.json.JSONObject;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    import java.io.*;
    
    
    @Controller
    @RequestMapping("/file")
    public class FileUploadController{
    
        @ResponseBody
        @RequestMapping(value="/upload", method= RequestMethod.POST,produces="text/html;charset=UTF-8")
        public String fileUpload(@RequestParam("myfile") MultipartFile file){
            String fileName = file.getOriginalFilename().substring(0,file.getOriginalFilename().length()-5);
            String str = "";
            try {
                InputStreamReader inputStreamReader = new InputStreamReader(file.getInputStream(),"UTF-8");
                BufferedReader br = new BufferedReader(inputStreamReader);
                String s= "";
                while ((s = br.readLine()) != null) {
                    str +=s;
                }
                br.close();
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            JSONObject jo = new JSONObject(str);
            jo.put("fileName",fileName);
            System.out.println(jo.toString());
            return jo.toString();
        }
    }
    

    相关文章

      网友评论

        本文标题:读取json文件

        本文链接:https://www.haomeiwen.com/subject/xptjuftx.html