我一直在尝试将一些对象序列化为System.out(用于调试)。我一打电话
final JsonSerializer serializer = new JsonSerializer();
serializer.serialize( System.out, myObj );
System.out.println("done");
它打印出json,但“完成”永远不会被打印出来。调试这些行,清楚地表明第3行被执行,但输出从不显示。
这是杰克森的错误,还是我做错了什么?
编辑:
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();
}
}
}
答案 0 :(得分:9)
由于其他用户的所有答案都已删除,我将回答我自己的问题。感谢用户声明这是jackson自动关闭输入流的问题。
解决方案是将JsonGenerator.Feature.AUTO_CLOSE_TARGET
添加到配置中,并将其设置为false:
mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
答案 1 :(得分:0)
如果不想将Mapson的JsonGenerator.Feature.AUTO_CLOSE_TARGET标志设置为false,则可以通过以下方式包装System.out以防止其被映射器关闭。
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();
}