java - 如何从Zip文件中提取Json数据并将提取的Json文件发送到前端?

标签 java mysql spring

我已经下载了包含json文件的zip文件,并在后端提取了文件(我们在java环境中)。我的下一步是将提取的 json 文件发送到前端 (Angular 7)。

String zipName = "facebook-srikanthmukku.zip";

    try (FileInputStream fis = new FileInputStream(zipName);
         ZipInputStream zis =
             new ZipInputStream(new BufferedInputStream(fis))) {

        ZipEntry entry;

        // Read each entry from the ZipInputStream until no
        // more entry found indicated by a null return value
        // of the getNextEntry() method.
        while ((entry = zis.getNextEntry()) != null) {
            System.out.println("Unzipping: " + entry.getName());

            int size;
            byte[] buffer = new byte[2048];

            try (FileOutputStream fos =
                     new FileOutputStream(entry.getName());
                 BufferedOutputStream bos =
                     new BufferedOutputStream(fos, buffer.length)) {

                while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                    bos.write(buffer, 0, size);
                }
                bos.flush();
            }
        }
    } catch (IOException e) {

        e.printStackTrace();
    }
}

最佳答案

在java中,您可以像下面这样读取.json文件并将其转换为JSONObject

JSONObject readObject = new JSONObject( (IOUtils.toString( new FileInputStream( filePath ),  StandardCharsets.UTF_8) ))

如果您使用 Spring Rest,在 Controller 中您可以这样做

@CrossOrigin
@RequestMapping(value = "jsonfile", method = RequestMethod.GET, produces = "application/json")
public String returnJson()
{

    JSONObject readObject = new JSONObject( (IOUtils.toString( new FileInputStream( filePath ),  StandardCharsets.UTF_8) ))

     return readObject.toString();
}

然后,您可以通过使用上述指定 URL 的 get 方法创建服务来在 Angular 应用程序中使用。

如果您已在本地主机和端口 8080 中启动 java spring 应用程序,您的 Angular 服务应如下所示

import { Injectable } from '@angular/core';
import { Observable, of, observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';    

@Injectable({
providedIn: 'root'
})
export class jsonService{

constructor(private httpClient:HttpClient) { }

public getJsonFiles(): Observable<any[]>{
 return this.httpClient.get<any>('http:/localhost:8080/jsonfile')
}
}

关于java - 如何从Zip文件中提取Json数据并将提取的Json文件发送到前端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55951476/

相关文章:

java - 我在设置 spring hibernate application-context.xml 时遇到问题

java - 温度Java程序

java - 如何将充满标记的 Object[] 转换为整数数组?

mysql - 我无法恢复我在 PhpMyAdmin 中的所有权限

mysql - 删除:Column count doesn't match value count at row 1时

spring - 如何构建 Spring Cloud Stream JMS ActiveMQ

java - Spring TimerFactoryBean 如何启动定时器任务

java - 从指定路径获取文件

java - 在源文件 java 中包含测试

MySQL LEFT OUTER JOIN 不过滤记录