Brandon
Brandon

Reputation: 4523

Formatting JSON before writing to File

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!

Upvotes: 8

Views: 21335

Answers (4)

vtsamis
vtsamis

Reputation: 1474

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

Upvotes: 5

Sohan
Sohan

Reputation: 6809

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

Upvotes: 2

Marco Lackovic
Marco Lackovic

Reputation: 6487

You need to configure the mapper beforehand as follows:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
mapper.writeValue(myFile, myJsonObjectNode);

Upvotes: 4

Subin Sebastian
Subin Sebastian

Reputation: 10997

try creating Object Writer like this

 ObjectWriter writer = mapper.defaultPrettyPrintingWriter();

Upvotes: 8

Related Questions