【发布时间】:2015-05-27 08:30:22
【问题描述】:
我有一个由 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?。
【问题讨论】:
-
你原来的 byteObj 数组的长度应该是 154...
-
你确定你的字节数组是文本吗?我的意思是,也许 Byte 数组是一个图像,并且字节不能转换为 String 中的有效字符:这就是长度不同的原因。
-
投反对票有什么理由吗?你连这个问题都看懂了吗?
-
不,如果字节数组的大小是一些,比如说小于130,这两个是一样的,当大于某个阈值时,它会失败。
-
你能以某种方式发布字节数组吗?只是一个猜测:也许这是字节顺序标记的问题。我觉得开头是
U+FEFF。