Roman K
Roman K

Reputation: 3337

Jackson JSON - serialize Streams

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.

Upvotes: 3

Views: 4965

Answers (2)

hzpz
hzpz

Reputation: 7911

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;
}

Upvotes: 2

tombrown52
tombrown52

Reputation: 492

Your question is similar to: Jackson JSON custom serialization for certain fields

What is the desired behavior? Do you want the stream to be serialized as a string, as binary content, parsed and serialized as an object, etc.

Assuming you want the data serialized as a string, you could use an annotation to tell Jackson how to serialize it:

public class TextFile {
    String fileName;
    @JsonSerialize(using=ReaderToStringSerializer.class, as=String.class)
    StringReader content;
}


public class ReaderToStringSerializer extends JsonSerializer<Reader> {

@Override
public void serialize(Reader contents, 
                      JsonGenerator jsonGenerator, 
                      SerializerProvider serializerProvider) 
                      throws IOException, JsonProcessingException {
    StringBuilder buffer = new StringBuilder();
    char[] array = new char[8096];
    int len = 0;
    while (-1 != (len = contents.read(array))) {
        buffer.append(array,0,len);
    }
    contents.close();
    jsonGenerator.writeString(buffer.toString());
}

The output would be something like:

{
  "fileName": "foo.bar",
  "content": "the quick brown fox..."
}

Upvotes: 0

Related Questions