【问题标题】:Exporting a JSON String to file将 JSON 字符串导出到文件
【发布时间】:2017-04-28 11:58:41
【问题描述】:

我使用 phonegap 创建了一个 Android 移动应用程序,我正在寻找一种方法来导出 strifiified json 数据集。我以这种方式对我的 json 进行了标记:

var storageObj = mydata.toGeoJSON();
var data = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(storageObj));

然后我尝试了:

var dlAnchorElem = document.getElementById('downloadAnchorElem');
dlAnchorElem.setAttribute("href",     data     );
dlAnchorElem.setAttribute("download", "data.js");
dlAnchorElem.click();

<a id="downloadAnchorElem" style="display:none"></a>

虽然它可以在台式电脑上运行,但它不能在我的移动应用程序上运行。

我应该如何将字符串化的 json 导出到文件并存储或(如果更容易实现)通过电子邮件发送?

【问题讨论】:

    标签: android json file export phonegap


    【解决方案1】:

    获取 json 对于 JAVA,使用 Gson 库。

    JsonParser parser = new JsonParser();
    JsonObject json = parser.parse(jsonString).getAsJsonObject();
    
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String prettyJson = gson.toJson(json); 
        /**
         * Dump the json in file.
         */
    try(PrintWriter out = new PrintWriter("PATH/" + "YOUR_FILE_NAME.txt")){
            out.println( json);
    }catch(java.io.FileNotFoundException e){
        e.printstacktrace();
    }
    
    1. 如果您正在使用 android 应用程序,请将其依赖项放在 build.gradle 文件中。dependency details
    2. 对于普通的 JAVA 项目,enter link description here 下载 JAR。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 2014-09-26
      • 2013-06-01
      • 2014-06-24
      • 1970-01-01
      • 2014-11-16
      相关资源
      最近更新 更多