Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - Using custom PrettyPrinter with custom JsonSerializer

I am using Jackson v2.8.2 to serialise JSON to a file.

I have created a custom serializer and implemented the serialize method to customise the JSON output as required.

I am invoking the serializer as follows:

// 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) 
{
    ...
}

The JSON file is created and the content looks good.

The file is formatted according to the DefaultPrettyPrinter but I want to use my own custom PrettyPrinter, which I have already implemented.

How do I do that?

I've tried the following:

MyPrettyPrinter myPrettyPrinter = new MyPrettyPrinter();
mapper.writer(myPrettyPrinter);
mapper.writeValue(new File("json.txt"), myClass);

but that isn't invoking my custom printer.

like image 247
ksl Avatar asked Dec 29 '25 00:12

ksl


1 Answers

Sometimes, depending on what you want to achieve, you could use the DefaultPrettyPrinter and just customize the Indenter, as following:

DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
Indenter indenter = new CustomSpaceIndenter();
printer.indentObjectsWith(indenter); // Indent JSON objects
printer.indentArraysWith(indenter);  // Indent JSON arrays

There's a related question about it: Serialize JsonNode to a very specific JSON format in Jackson

like image 177
cassiomolin Avatar answered Dec 30 '25 13:12

cassiomolin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!