我正在使用Jackson v2.8.2将JSON序列化为文件。Jackson - 将自定义PrettyPrinter与自定义JsonSerializer一起使用
我已经创建了一个自定义序列化器并实现了serialize
方法来根据需要自定义JSON输出。
我调用串行如下:
// myClass is the object I want to serialize
SimpleModule module = new SimpleModule();
module.addSerializer(MyClass.class, new MySerializer());
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
mapper.registerModule(module);
try
{
mapper.writeValue(new File("json.txt"), myClass);
}
catch (JsonProcessingException e)
{
...
}
创建的JSON文件和内容看起来不错。
该文件格式根据DefaultPrettyPrinter
,但我想用我自己定制PrettyPrinter
,我已经实现。
我该怎么做?
我已经试过如下:
MyPrettyPrinter myPrettyPrinter = new MyPrettyPrinter();
mapper.writer(myPrettyPrinter);
mapper.writeValue(new File("json.txt"), myClass);
但那不是我的调用自定义打印机。
如果我按照您的建议更改代码,它不会编译 - 类型不匹配:cann不要从ObjectWriter转换为ObjectMapper'。 – ksl
@ksl你是对的。我道歉,我更新了我的答案。您必须将作者分配给一个变量并使用该变量 – pandaadb
谢谢,这很有用。还要注意''mapper.setDefaultPrettyPrinter(new MyPrettyPrinter())'也适用。我偶然发现了这里 - https://github.com/FasterXML/jackson-databind/issues/689。 – ksl