问题
How is a JSONObject
from Twitter4J
converted to an IOFile
for use with the JsonParser
from BaseX
?
So, looking to use Twitter4J
to get either a file or stream.
The JsonParser
looks to work with a File
fine:
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
although other IO
works:
org.basex.io
Class IO
java.lang.Object
org.basex.io.IO
Direct Known Subclasses:
IOContent, IOFile, IOStream, IOUrl
How is a File
acquired from a JSONObject
here?
Snippet using 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;
}
回答1:
Writing a JSONObject
to file file from Twitter4J
seems to work, at least the file looks correct when opened manually:
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();
}
And once the file is written, it seems quite easy to "parse" the JSON
, or at least instantiate a parser, as:
private void parseJsonFile(String fileName) throws IOException {
JsonParser jsonParser = new JsonParser(new IOFile(fileName), new MainOptions());
}
full code on github.
In no way is this a complete solution. In fact, it seems a kludge to write the JSON
to a file at all -- but there it is.
Seems the only way to move JSON
data from Twitter4J
to BaseX
, or at least most pragmatic. Other solutions appreciated.
来源:https://stackoverflow.com/questions/60015248/how-to-get-a-file-or-stream-from-a-jsonobject