Custom pretty printer using Jackson library
Asked Answered
I

1

12

I have data in a Map object and I want to print it in a json format. I tried using DefaultPrettyPrinter

mapper.writerWithDefaultPrettyPrinter().writeValue(filePath, mapObject);

but the format is not what I expected. I am getting output like this:

{
  "arrVals" : ["value-1","value-2"]
}

I want output like this:

{
  "arrVals" : [
    "value-1",
    "value-2"
  ]
}
Ison answered 7/8, 2013 at 8:35 Comment(3)
There is a simmilar question here: #6177381 (NOT a duplicate in my opinion) that can help youDactylo
I have seen that but it doesn't solve the problem. I need printing array values in next line.Ison
Similar question: #17412086Avowed
M
21

You need indentation before Array Values. You can use indentArraysWith method to set the Lf2SpacesIdenter object which will basically add a line feed followed by 2 spaces. This might solve your problem.

DefaultPrettyPrinter pp = new DefaultPrettyPrinter();
pp.indentArraysWith(new Lf2SpacesIndenter());
mapper.writer(pp).writeValue(filePath, mapObject);
Malignant answered 7/8, 2013 at 8:48 Comment(1)
Lf2SpacesIndenter is at DefaultPrettyPrinter.Lf2SpacesIndenter The constructor and instance field are deprecated. Use: pp.indentArraysWith( DefaultIndenter.SYSTEM_LINEFEED_INSTANCE );Zeniazenith

© 2022 - 2024 — McMap. All rights reserved.