我已经下载了包含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();
}
}
答案 0 :(得分:0)
在Java中,您可以读取如下的.json文件并将其转换为JSONObject
JSONObject readObject = new JSONObject( (IOUtils.toString( new FileInputStream( filePath ), StandardCharsets.UTF_8) ))
如果您使用的是Spring Rest,则可以在控制器中这样做
@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应用程序中使用。
如果您已在localhost和端口8080中启动了java spring应用程序,则您的角度服务应如下所示
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')
}
}