如何使用 GSON 从 Primeface 应用程序下载 json 文件?
How to download a json file from Primeface app using GSON?
我需要从我的应用程序下载文件 .json
,但要选择它的位置。
我知道如何将文件下载到磁盘,例如图片 <p:fileDownload value=""/>
public StreamedContent getFile(){
return new DefaultStreamedContent(stream, "image/jpg", "img.jpg");
}
我知道如何使用给定路径 GSON
写入文件
try(JsonWrite j = new JsonWriter(new OutputStreamWriter(
new FileOutputStream("C:\...\...\file.json"), "UTF-8"))){
j.beginObject();
// ...
j.name("foo");
gson.toJson(myObj, Foo.class, j);
//...
j.endObject();
}catch(...){...}
但我不知道如何将两者结合起来才能选择位置并在此位置写入 json?
所以我不认为你可以为所欲为。您所能做的就是流式传输您的 JSON 文件并为其命名,例如 "test.json"。出于安全原因,您不能告诉浏览器您希望用户下载的位置。我相信它类似于此请求:Browsing file system to select directory in JSF
如果您只是想发送一个 GSON 文件以供用户下载。
XHTML:
<p:fileDownload value="#{myController.downloadFile()}" />
JAVA:
public StreamedContent downloadFile() {
// convert GSON object to InputStream
String gson= json.getJSONObject("data").toString();
InputStream stream = new ByteArrayInputStream(gson.getBytes());
DefaultStreamedContent content = new DefaultStreamedContent(stream,
MediaType.APPLICATION_JSON,
"test.json");
return content;
}
我需要从我的应用程序下载文件 .json
,但要选择它的位置。
我知道如何将文件下载到磁盘,例如图片
<p:fileDownload value=""/>
public StreamedContent getFile(){ return new DefaultStreamedContent(stream, "image/jpg", "img.jpg"); }
我知道如何使用给定路径
GSON
写入文件try(JsonWrite j = new JsonWriter(new OutputStreamWriter( new FileOutputStream("C:\...\...\file.json"), "UTF-8"))){ j.beginObject(); // ... j.name("foo"); gson.toJson(myObj, Foo.class, j); //... j.endObject(); }catch(...){...}
但我不知道如何将两者结合起来才能选择位置并在此位置写入 json?
所以我不认为你可以为所欲为。您所能做的就是流式传输您的 JSON 文件并为其命名,例如 "test.json"。出于安全原因,您不能告诉浏览器您希望用户下载的位置。我相信它类似于此请求:Browsing file system to select directory in JSF
如果您只是想发送一个 GSON 文件以供用户下载。
XHTML:
<p:fileDownload value="#{myController.downloadFile()}" />
JAVA:
public StreamedContent downloadFile() {
// convert GSON object to InputStream
String gson= json.getJSONObject("data").toString();
InputStream stream = new ByteArrayInputStream(gson.getBytes());
DefaultStreamedContent content = new DefaultStreamedContent(stream,
MediaType.APPLICATION_JSON,
"test.json");
return content;
}