Question

I've been trying to serialize some Objects to System.out (for debugging). As soon as I call

final JsonSerializer serializer = new JsonSerializer();
serializer.serialize( System.out, myObj );
System.out.println("done");

it prints out the json, but the "done" never gets printed. Debugging these lines, clearly shows that the 3rd line gets executed, but the output never shows up.

Is this a jackson bug, or am I doing anything wrong?

EDIT:

public class JsonSerializer
{

private ObjectMapper getConfiguredObjectMapper()
{
  final ObjectMapper mapper = new ObjectMapper();
  mapper.enable( SerializationConfig.Feature.INDENT_OUTPUT );
  mapper.setVisibility( JsonMethod.FIELD, Visibility.ANY );
  mapper.setVisibility( JsonMethod.GETTER, Visibility.NONE );
  mapper.configure( SerializationConfig.Feature.AUTO_DETECT_GETTERS, false );
  mapper.configure( SerializationConfig.Feature.AUTO_DETECT_IS_GETTERS, false );
  mapper.configure( SerializationConfig.Feature.AUTO_DETECT_FIELDS, false );



  final SimpleModule module = new SimpleModule( "ConnectorSerialization", new Version( 0, 1, 0, null ) );
  module.addSerializer( new InputConnectorSerializer() );
  module.addSerializer( new OutputConnectorSerializer() );
  module.addSerializer( new StateSerializer() );
  mapper.registerModule( module );

  return mapper;
  }


public void serialize( final OutputStream outputStream, final Object root )
{


  final ObjectMapper mapper = getConfiguredObjectMapper();


  try
  {
     mapper.writeValue( outputStream, root );

  }
  catch (final JsonGenerationException e)
  {
     // TODO Auto-generated catch block
     e.printStackTrace();
  }
  catch (final JsonMappingException e)
  {
     // TODO Auto-generated catch block
     e.printStackTrace();
  }
  catch (final IOException e)
  {
     // TODO Auto-generated catch block
     e.printStackTrace();
  }

}
}
Était-ce utile?

La solution

As all answers by other users got deleted, I am going to answer my own question. Thanks to the user that stated that this is an issue where jackson closes the input stream automatically.

The solution is to add JsonGenerator.Feature.AUTO_CLOSE_TARGET to the configuration, and set it to false:

mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);

Autres conseils

You can wrap System.out in the following way to prevent it being closed by the mapper, if you wouldn't like to set JsonGenerator.Feature.AUTO_CLOSE_TARGET flag to false for the mapper.

public <T> void println(T t) throws IOException {
    objectMapper.writeValue(new OutputStream() {
        @Override
        public void write(int i) throws IOException {
            System.out.write(i);
        }
    }, t);
    System.out.println();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top