我正在尝试通过使用 ObjectMapper 记录响应,将复杂对象序列化为内部包含字节缓冲区的字符串。这会改变字节缓冲区内的光标位置,并且只会破坏响应。
我正在使用的代码片段:
import org.codehaus.jackson.map.ObjectMapper;
private static final ObjectMapper MAPPER = new ObjectMapper();
public static String serializeToString(final Object obj) {
Preconditions.checkArgument(obj != null, "Object to be serialized is null");
try {
final String str = MAPPER.writeValueAsString(obj);
if (Strings.isNullOrEmpty(str)) {
log.warn("Serialized to null/empty string");
}
return str;
} catch (final JsonGenerationException e) {
throw new IllegalArgumentException("Json generation exception occured in de-serializing obj", e);
} catch (final JsonMappingException e) {
throw new IllegalArgumentException("Json mapping exception occured in de-serializing obj", e);
} catch (final IOException e) {
throw new IllegalArgumentException("IO exception occured in de-serializing obj", e);
}
}
我在上面的方法中传递了一个内部有字节缓冲区的复杂对象。我在调用上述方法之前和之后打印了 bytebuffer。
public static void main(final String[] args) throws SecurityException, NoSuchMethodException {
final String x =
"Random data i am using for this test for byte buffer. Random data i am using for this test for byte buffer";
final byte[] byteArr = x.getBytes();
final ByteBuffer bb = ByteBuffer.wrap(byteArr);
System.out.println("before bytebuffer :" + bb);
String stringData = SerializerUtil.serializeToString(bb); // In real i am passing a complex structure having
// bytebuffer inside
System.out.println(stringData);
System.out.println("after bytebuffer :" + bb);
}
输出:
before bytebuffer :java.nio.HeapByteBuffer[pos=0 lim=106 cap=106]
{"short":21089,"char":"\u6e64","int":1869422692,"long":7022344510808023405,"float":2.0790493E-19,"double":6.687717052371733E223,"direct":false,"readOnly":false}
after bytebuffer :java.nio.HeapByteBuffer[pos=28 lim=106 cap=106]
(pos=0 到 pos=28) 位置的这种变化只会破坏发送的响应。我们有什么方法可以在不影响 byteBuffer 的情况下将这个复杂对象转换为字符串?
非常感谢任何帮助。