【问题标题】:How to get a File or Stream from a JSONObject?如何从 JSONObject 获取文件或流?
【发布时间】:2020-05-17 19:02:53
【问题描述】:

如何将来自Twitter4JJSONObject 转换为IOFile 以与来自BaseXJsonParser 一起使用?

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

JsonParser 看起来像 work withFile 很好:

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 

File 是如何从这里的JSONObject 获得的?

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;
}

【问题讨论】:

  • 是什么让您认为文件是或可以是“获得”的?在使用 Twitter 提要时为什么需要文件?
  • 如何将对象转换为字符串并将该字符串写入文件?
  • 使用流?专门来自字符串的ByteArrayInputStream
  • @Thufir 是的,但我的意思是没有先写信给File。我很确定JSonParser 可以从InputStream 中读取,您可以从String.getBytes(charset) 中获得ByteArrayInputStream。或ReaderStringReader。啊,Basic IO,你怎么被遗忘了。
  • 是 BaseX 库把事情扔掉了,但是不,您不需要将内容存储到文件中并读回内存中已有的内容。

标签: java json xml twitter4j basex


【解决方案1】:

JSONObjectTwitter4J 写入文件似乎可行,至少手动打开文件时看起来正确:

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 的唯一方法,或者至少是最实用的方法。其他解决方案表示赞赏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 2013-02-19
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    相关资源
    最近更新 更多