Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson JSON - serialize Streams

Tags:

java

json

jackson

Is there a way to make Jackson serialize some stream object (and close after)? like this:

class TextFile{
    String fileName;
    StringReader content;
    //ByteArrayInputStream content;
}

Update

Clarification: I want to stream the content, not just serialize it to a single String object.

like image 437
Roman K Avatar asked Jul 31 '26 03:07

Roman K


1 Answers

Implement a custom JsonSerializer:

public class StreamSerializer extends JsonSerializer<ByteArrayInputStream> {

    @Override
    public void serialize(ByteArrayInputStream content, 
                          JsonGenerator jsonGenerator, 
                          SerializerProvider serializerProvider) 
                          throws IOException, JsonProcessingException {
        jsonGenerator.writeBinary(content, -1);
}

And use it like this:

public class TextFile {
    String fileName;
    @JsonSerialize(using=StreamSerializer.class, as=byte[].class)
    ByteArrayInputStream content;
}
like image 140
hzpz Avatar answered Aug 02 '26 17:08

hzpz