杰克逊序列化后 System.out 出了问题。

8

我一直在尝试将一些对象序列化到System.out(用于调试)。 一旦我调用

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

它打印出了JSON,但是“done”从未被打印。调试这些行时,很明显第3行被执行了,但输出从未显示。

这是Jackson的一个错误还是我的操作有误?

编辑:

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

}
}
2个回答

12

由于其他用户的回答都被删除了,我将回答自己的问题。感谢那位指出这是一个Jackson自动关闭输入流的问题的用户。

解决方案是在配置中添加 JsonGenerator.Feature.AUTO_CLOSE_TARGET 并将其设置为false:

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

2
你应该接受自己的答案,因为它是正确的! :) - Matt Ball

0
您可以通过以下方式包装System.out,以防止它被映射器关闭,如果您不想为映射器设置JsonGenerator.Feature.AUTO_CLOSE_TARGET标志为false。
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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接