ObjectMapper writeValueAsString更改bytebuffer pos

时间:2013-06-25 07:38:51

标签: java

我试图通过使用ObjectMapper记录响应来将一个复杂对象序列化为某个地方包含bytebuffer的字符串。 这会改变bytebuffer中的光标位置,只会破坏响应。

我正在使用的代码段:

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的复杂对象。 我在调用上面的方法之前和之后打印了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?

任何帮助都非常感激。

1 个答案:

答案 0 :(得分:1)

显然,您不希望将ByteBuffer属性序列化为另一个结构化类,而只是将内容序列化为字符串。一种方法是在方法上使用@JsonProperty注释来告诉映射器使用该方法,而不是尝试直接序列化字段。假设你有这样的bean:

class Stuff {

    private ByteBuffer data;

    public Stuff() {
    }

    public Stuff(ByteBuffer data) {
        super();
        this.data = data;
    }

    public ByteBuffer getData() {
        return data;
    }

    public void setData(ByteBuffer data) {
        this.data = data;
    }

    @JsonProperty(value = "data")
    public String convertData() {
        return new String(data.array());
    }

    @JsonProperty("data")
    public void convertData(String s) {
        data = ByteBuffer.wrap(s.getBytes());
    }

}

映射器现在将使用convertData方法对ByteBuffer数据属性进行序列化和反序列化,您仍然可以使用普通的java bean属性方法。

更新

由于无法更改序列化类,因此这是使用som高级JACKSON内容的替代方法。首先,创建自定义序列化程序和反序列化程序:

static class ByteBufferSerializer extends JsonSerializer<ByteBuffer> {

    @Override
    public void serialize(ByteBuffer value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jgen.writeString(new String(value.array()));
    }
}

static class ByteBufferDeserializer extends JsonDeserializer<ByteBuffer> {

    @Override
    public ByteBuffer deserialize(JsonParser jp,
            DeserializationContext context) throws IOException,
            JsonProcessingException {
        return ByteBuffer.wrap(jp.getText().getBytes());
    }

}

然后,创建一个Mixin接口,为我们在真实目标类中无法提供的属性提供注释:

static interface Mixin {

    @JsonSerialize(using = ByteBufferSerializer.class, contentAs = String.class)
    ByteBuffer getData();

    @JsonDeserialize(using = ByteBufferDeserializer.class, contentAs = String.class)
    void setData(ByteBuffer data);

}

此外,创建一个用于配置对象映射器的模块,并添加mixin接口:

static class MyModule extends SimpleModule {
    public MyModule() {
        super("ByteBuffer wrangling");
    }

    @Override
    public void setupModule(SetupContext context) {
        context.setMixInAnnotations(Stuff.class, Mixin.class);
    }
}

最后,使用映射器注册模块:

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new MyModule());

Voilà,小菜一碟! : - )