为什么杰克逊这种漂亮的打印功能不起作用? [英] Why doesn't this Jackson pretty print function work?
本文介绍了为什么杰克逊这种漂亮的打印功能不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么杰克逊这种漂亮的印刷功能不起作用?只是尝试读取文件并使用jackson api打印它:
Why doesn't this Jackson pretty print function work? Just trying to read a file and pretty print it using jackson api:
public static void printJsonFromFile( String fileName ) {
System.out.println("-----------------");
ObjectMapper mapper = new ObjectMapper();
try {
System.out.println( mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString( readFile( fileName, StandardCharsets.UTF_8 )) );
} catch ( IOException e ) {
e.printStackTrace();
}
System.out.println("-----------------");
}
static String readFile(String path, Charset encoding) throws IOException
{
byte[] encoded = Files.readAllBytes( Paths.get( path ) );
return encoding.decode( ByteBuffer.wrap( encoded ) ).toString();
}
推荐答案
您可以替换 System.out
使用以下内容进行调用:
You can replace your System.out
call with the following:
Object json = mapper.readValue(readFile(fileName, StandardCharsets.UTF_8), Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
这应该正确缩进你的json。
This should properly indent your json.
希望这会有所帮助。
这篇关于为什么杰克逊这种漂亮的打印功能不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文