java - 如何从 JSONObject 获取文件或流?

标签 java json xml twitter4j basex

如何将 Twitter4J 中的 JSONObject 转换为 IOFile 以与 BaseX 中的 JsonParser 一起使用?

因此,希望使用 Twitter4J 来获取文件或流。

JsonParser 查找 work with一个文件很好:

JsonParser

public JsonParser(IO source,
          MainOptions opts,
          JsonParserOptions jopts)
           throws java.io.IOException

Constructor.

Parameters:
    source - document source
    opts - database options
    jopts - parser options
Throws:
    java.io.IOException - I/O exception

虽然其他IO有效:

org.basex.io
Class IO

    java.lang.Object
        org.basex.io.IO 

    Direct Known Subclasses:
        IOContent, IOFile, IOStream, IOUrl 

这里如何从 JSONObject 获取 File

Snippet使用 Twitter4J:

private JSONObject jsonOps(Status status) throws JSONException, BaseXException {
    String string = TwitterObjectFactory.getRawJSON(status);
    JSONObject json = new JSONObject(string);
    String language = json.getString("lang");
    log.fine(language);
    return json;
}

最佳答案

JSONObject 写入来自 Twitter4J 的文件似乎可行,至少手动打开时文件看起来是正确的:

public void writeJsonToFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException, IOException {
    FileOutputStream fileOutputStream = null;
    OutputStreamWriter outputStreamWriter = null;
    BufferedWriter bufferedWriter = null;
    fileOutputStream = new FileOutputStream(fileName);
    outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
    bufferedWriter = new BufferedWriter(outputStreamWriter);
    bufferedWriter.write(tweets.toString());
    bufferedWriter.close();
    outputStreamWriter.close();
    fileOutputStream.close();
}

一旦写入文件,“解析”JSON 似乎很容易,或者至少实例化一个解析器,如下所示:

private void parseJsonFile(String fileName) throws IOException {
    JsonParser jsonParser = new JsonParser(new IOFile(fileName), new MainOptions());
}

github 上的完整代码.

这绝不是一个完整的解决方案。事实上,将 JSON 写入文件似乎是一件很麻烦的事情——但事实就是如此。

似乎是将 JSON 数据从 Twitter4J 移动到 BaseX 的唯一方法,或者至少是最实用的方法。其他解决方案表示赞赏。

关于java - 如何从 JSONObject 获取文件或流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60015248/

相关文章:

json - 三元条件flutter的使用方法

android - JSONObject解析

python - 如何使用 libsbml 读取 sbml 文件的属性

java - 使用 Joox 解析 Xml 字符串

java - 使用 JAXB 注释外部库中的对象

java - 如何在android中检查互联网和服务器(url)的可用性

json - jQuery ajax jsonp 调用成功后出现错误

java - 如何设置按钮上的文字颜色? java

java - hibernate 搜索 : Store List of Children and retrieve via projection

java - 如何根据换行符分割java字符串