Java 如何从 JsonObject 创建 InputStream 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23816356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Create InputStream Object from JsonObject
提问by This 0ne Pr0grammer
I'm trying to figure out how one goes about retrieving the raw bytes stored in a JsonObject and turns that into an InputStream object?
我想弄清楚如何检索存储在 JsonObject 中的原始字节并将其转换为 InputStream 对象?
I figured it might be something like:
我想它可能是这样的:
InputStream fis = new FileInputStream((File)json.getJsonObject("data"));
Granted I haven't tried that out, but just wanted to know if anyone had any experience with this and knew the preferred way to do it?
当然,我还没有尝试过,但只是想知道是否有人对此有任何经验并知道首选的方法吗?
采纳答案by Chthonic Project
You can convert a JSONObject
into its String
representation, and then convert that String into an InputStream
.
您可以将 aJSONObject
转换为其String
表示形式,然后将该字符串转换为InputStream
.
The code in the question has a JSONObject being cast into File
, but I am not sure if that works as intended. The following, however, is something I have done before (currently reproduced from memory):
问题中的代码有一个 JSONObject 被转换为File
,但我不确定这是否按预期工作。然而,以下是我之前做过的事情(目前从记忆中复制):
String str = json.getJSONObject("data").toString();
InputStream is = new ByteArrayInputStream(str.getBytes());
Note that the toString()
method for JSONObject
overrides the one in java.lang.Object
class.
请注意,toString()
用于JSONObject
覆盖java.lang.Object
类中的方法。
From the Javadoc:
从Javadoc:
Returns:a printable, displayable, portable, transmittable representation of the object, beginning with { (left brace) and ending with } (right brace).
返回: 对象的可打印、可显示、可移植、可传输表示,以 {(左括号)开头,以 }(右括号)结尾。
回答by Yazan
if you want bytes, use this
如果你想要字节,使用这个
json.toString().getBytes()
or write a File savedFile
contains json.toString, and then
或者写一个savedFile
包含json.toString的文件,然后
InputStream fis = new FileInputStream(savedFile);