我有一个由 BSON 序列化的字节数组 byteObj
。
String strObj = new String(byteObj)
System.out.println(byteObj.length)
System.out.println(strObj.getBytes().length)
结果是 152
和 154
。而且这两个字节数组并不相同。如何从字符串中恢复原始的 bson 字节数组?
更新:
152 154
[-104, 0, 0, 0, 4, 116, 105, 116, 108, 101, 0, 80, 0, 0, 0, 2, 48, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 49, 0, 3, 0, 0, 0, 105, 115, 0, 2, 50, 0, 2, 0, 0, 0, 97, 0, 2, 51, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 52, 0, 2, 0, 0, 0, 97, 0, 2, 53, 0, 3, 0, 0, 0, 105, 115, 0, 2, 54, 0, 6, 0, 0, 0, 116, 105, 116, 108, 101, 0, 0, 4, 99, 111, 110, 116, 101, 110, 116, 0, 51, 0, 0, 0, 2, 48, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 49, 0, 2, 0, 0, 0, 97, 0, 2, 50, 0, 8, 0, 0, 0, 99, 111, 110, 116, 101, 110, 116, 0, 2, 51, 0, 3, 0, 0, 0, 105, 115, 0, 0, 0]
[-17, -65, -67, 0, 0, 0, 4, 116, 105, 116, 108, 101, 0, 80, 0, 0, 0, 2, 48, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 49, 0, 3, 0, 0, 0, 105, 115, 0, 2, 50, 0, 2, 0, 0, 0, 97, 0, 2, 51, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 52, 0, 2, 0, 0, 0, 97, 0, 2, 53, 0, 3, 0, 0, 0, 105, 115, 0, 2, 54, 0, 6, 0, 0, 0, 116, 105, 116, 108, 101, 0, 0, 4, 99, 111, 110, 116, 101, 110, 116, 0, 51, 0, 0, 0, 2, 48, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 49, 0, 2, 0, 0, 0, 97, 0, 2, 50, 0, 8, 0, 0, 0, 99, 111, 110, 116, 101, 110, 116, 0, 2, 51, 0, 3, 0, 0, 0, 105, 115, 0, 0, 0]
第一个是 BSON 字节数组。
更新2: 测试代码
BSONObject ob = new BasicBSONObject()
.append("title", Arrays.asList(new String[]{"this", "is", "a", "this", "a", "is", "title"}))
.append("content", Arrays.asList(new String[]{"this", "a", "content", "is"}));
byte[] ahaha = BSON.encode(ob);
BSON.decode(ahaha);
// BSON.decode(new String(ahaha).getBytes());
byte[] strByte = new String(ahaha).getBytes();
System.out.println(ahaha.length + "\t" + strByte.length);
System.out.println(Arrays.toString(ahaha));
System.out.println(Arrays.toString(strByte));
参见How do you convert binary data to Strings and back in Java?用于将二进制数据转换为字符串以及反之亦然的解决方案。
最佳答案
差异的原因是字节到字符串的转换。注意第一个字节是负数。这是 Javadoc 的解释:
新字符串的长度是字符集的函数,因此可能不等于字节数组的长度。 当给定字节在默认字符集中无效时,此构造函数的行为未指定。
当需要对解码过程进行更多控制时,应使用 CharsetDecoder 类。
关于java - 与 string.getBytes() 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30477087/