Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting JSON before writing to File

Tags:

java

json

jackson

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!

like image 358
Brandon Avatar asked Jun 13 '12 04:06

Brandon


3 Answers

try creating Object Writer like this

 ObjectWriter writer = mapper.defaultPrettyPrintingWriter();
like image 148
Subin Sebastian Avatar answered Oct 05 '22 23:10

Subin Sebastian


You need to configure the mapper beforehand as follows:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
mapper.writeValue(myFile, myJsonObjectNode);
like image 32
Marco Lackovic Avatar answered Oct 06 '22 00:10

Marco Lackovic


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

like image 41
Sohan Avatar answered Oct 06 '22 01:10

Sohan