7

Currently I'm using the Jackson JSON Processor to write preference data and whatnot to files mainly because I want advanced users to be able to modify/backup this data. Jackson is awesome for this because its incredibly easy to use and, apparently performs decently (see here), however the only problem I seem to be having with it is when I run myObjectMapper.writeValue(myFile, myJsonObjectNode) it writes all of the data in the ObjectNode to one line. What I would like to do is to format the JSON into a more user friendly format.

For example, if I pass a simple json tree to it, it will write the following:

{"testArray":[1,2,3,{"testObject":true}], "anotherObject":{"A":"b","C":"d"}, "string1":"i'm a string", "int1": 5092348315}

I would want it to show up in the file as:

{
    "testArray": [
        1,
        2,
        3,
        {
            "testObject": true
        }
    ],
    "anotherObject": {
        "A": "b",
        "C": "d"
    },
    "string1": "i'm a string",
    "int1": 5092348315
}

Is anyone aware of a way I could do this with Jackson, or do I have to get the String of JSON from Jackson and use another third party lib to format it?

Thanks in advance!

amucunguzi
  • 1,203
  • 1
  • 12
  • 16
Brandon
  • 4,486
  • 8
  • 33
  • 39

4 Answers4

7

try creating Object Writer like this

 ObjectWriter writer = mapper.defaultPrettyPrintingWriter();
jmj
  • 237,923
  • 42
  • 401
  • 438
Subin Sebastian
  • 10,870
  • 3
  • 37
  • 42
  • 3
    ...wow. I thought I searched through the javadocs of every single function in ObjectMapper thoroughly. I can't believe I missed this. And I actually couldnt find `mapper.defaultPrettyPrintingWriter()` but found it actually as `mapper.writerWithDefaultPrettyPrinter()`. Thanks for the help! – Brandon Jun 13 '12 at 05:06
  • The function mismatch could be due to different versions. I'm using Jackson 2.0.2. – Brandon Jun 13 '12 at 05:08
  • `mapper.defaultPrettyPrintingWriter()` is actually deprecated in Jackson 1.9.2 – Marco Lackovic Mar 14 '13 at 13:15
4

You need to configure the mapper beforehand as follows:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
mapper.writeValue(myFile, myJsonObjectNode);
Marco Lackovic
  • 6,077
  • 7
  • 55
  • 56
3

To enable standard indentation in Jackson 2.0.2 and above use the following:

ObjectMapper myObjectMapper = new ObjectMapper();
myObjectMapper.enable(SerializationFeature.INDENT_OUTPUT);
myObjectMapper.writeValue(myFile, myJsonObjectNode)

source:https://github.com/FasterXML/jackson-databind

vtsamis
  • 1,384
  • 1
  • 12
  • 9
2

As per above mentioned comments this worked for me very well,

     Object json = mapper.readValue(content, Object.class);
     mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); 

Where content is your JSON string response

Jackson version:2.12

Sohan
  • 6,252
  • 5
  • 35
  • 56