我已经下载了包含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/