java 使用 JSONObject 放置/获取字节数组值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26650225/
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
Put/get byte array value using JSONObject
提问by Yubaraj
I tried to get my byte[]
value from JSONObject
using following code but I am not getting original byte[]
value.
我试图byte[]
通过JSONObject
使用以下代码获得我的价值,但我没有获得原始byte[]
价值。
JSONArray jSONArray = jSONObject.getJSONArray(JSONConstant.BYTE_ARRAY_LIST);
int len = jSONArray.length();
for (int i = 0; i < len; i++) {
byte[] b = jSONArray.get(i).toString().getBytes();
//Following line creates pdf file of this byte arry "b"
FileCreator.createPDF(b, "test PDF From Web Resource.pdf");
}
}
Above code creates pdf file but file can not open i.e corrupted file. But, when I use same class and method to create file:
上面的代码创建了 pdf 文件,但文件无法打开,即损坏的文件。但是,当我使用相同的类和方法来创建文件时:
FileCreator.createPDF(b, "test PDF From Web Resource.pdf");
before adding into JSONObject
like follwoing:
在添加JSONObject
如下之前:
JSONObject jSONObject = new JSONObject();
jSONObject.put(JSONConstant.BYTE_ARRAY_LIST, bList);
it creates file i.e I can open pdf file and read its content.
它创建文件,即我可以打开 pdf 文件并阅读其内容。
What I did wrong to get byte[]
from JSONObject
so that it is creating corrupted file? Please kindly guide me. And I always welcome to comments. Thank You.
我做错了什么让byte[]
来自JSONObject
使其产生损坏的文件?请指导我。我总是欢迎评论。谢谢。
回答by Yubaraj
Finally I solved my issue with the help of apache commonslibrary. First I added the following dependency.
最后我在apache commons库的帮助下解决了我的问题。首先我添加了以下依赖项。
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.6</version>
<type>jar</type>
</dependency>
The technique that I was using previously was wrong for me (Not sure for other). Following is the solution how I solved my problem.
我以前使用的技术对我来说是错误的(不确定其他人)。以下是我如何解决我的问题的解决方案。
Solution:
解决方案:
I added byte array value previously on JSONObject and stored as String. When I tried to get from JSONObject to my byte array it returned String not my original byte array. And did not get the original byte array even I use following:
我之前在 JSONObject 上添加了字节数组值并存储为字符串。当我尝试从 JSONObject 到我的字节数组时,它返回 String 而不是我的原始字节数组。即使我使用以下内容也没有得到原始字节数组:
byte[] bArray=jSONObject.getString(key).toString().getBytes();
Now,
现在,
First I encoded my byte array into string and kept on JSONObject. See below:
首先,我将字节数组编码为字符串并保留在 JSONObject 上。见下文:
byte[] bArray=(myByteArray);
//Following is the code that encoded my byte array and kept on String
String encodedString = org.apache.commons.codec.binary.Base64.encodeBase64String(bArray);
jSONObject.put(JSONConstant.BYTE_ARRAY_LIST , encodedString);
And the code from which I get back my original byte array:
以及我从中取回原始字节数组的代码:
String getBackEncodedString = jSONObject.getString(JSONConstant.BYTE_ARRAY_LIST);
//Following code decodes to encodedString and returns original byte array
byte[] backByte = org.apache.commons.codec.binary.Base64.decodeBase64(getBackEncodedString);
//Creating pdf file of this backByte
FileCreator.createPDF(backByte, "fileAfterJSONObject.pdf");
That's it.
而已。
回答by shark1608
This might be of help for those using Java 8. Make use of java.util.Base64
.
这可能对使用 Java 8 的人有所帮助。利用java.util.Base64
.
Encoding byte array to String :
将字节数组编码为 String :
String encodedString = java.util.Base64.getEncoder().encodeToString(byteArray);
JSONObject.put("encodedString",encodedString);
Decode byte array from String :
从 String 解码字节数组:
String encodedString = (String) JSONObject.get("encodedString");
byte[] byteArray = java.util.Base64.getDecoder().decode(encodedString);
回答by CamelTM
For tests example(com.fasterxml.Hymanson used):
对于测试示例(使用 com.fasterxml.Hymanson):
byte[] bytes = "pdf_report".getBytes("UTF-8");
Mockito.when(reportService.createPackageInvoice(Mockito.any(String.class))).thenReturn(bytes);
String jStr = new ObjectMapper().writeValueAsString(bytes).replaceAll("\\"", ""); // return string with a '\"' escape...
mockMvc.perform(get("/api/getReport").param("someparam", "222"))
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
...
.andExpect(jsonPath("$.content", is(jStr)))
;
回答by user
When inserting a byte array into a JSONObject the toString() method is invoked.
将字节数组插入 JSONObject 时,将调用 toString() 方法。
public static void main(String... args) throws JSONException{
JSONObject o = new JSONObject();
byte[] b = "hello".getBytes();
o.put("A", b);
System.out.println(o.get("A"));
}
Example output:
示例输出:
[B@1bd8c6e
so you have to store it in a way that you can parse the String into the original datatype.
所以你必须以一种可以将字符串解析为原始数据类型的方式存储它。