gpt4 book ai didi

java - 为什么这个 Jackson pretty-print 功能不起作用?

转载 作者:行者123 更新时间:2023-11-29 05:31:42 26 4
gpt4 key购买 nike

为什么这个 Jackson pretty-print 功能不起作用?只是尝试读取一个文件并使用 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 调用替换为以下内容:

Object json = mapper.readValue(readFile(fileName, StandardCharsets.UTF_8), Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));

这应该正确缩进您的 json。

希望这对您有所帮助。

关于java - 为什么这个 Jackson pretty-print 功能不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20864595/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com