I am trying to read a json file and update a specific field. I am able to get to the proper nested location, but when I save it back after update, I get lots of "rn" instead of the original formatting.
I have tried using two approaches for reading:
private LinkedHashMap get3rdJsonAsMap() {
objectMapper = new ObjectMapper();//.enable(SerializationFeature.INDENT_OUTPUT);
LinkedHashMap json = null;
try {
json = (LinkedHashMap)objectMapper.readValue(new File(this.mono3rdJsonPath), Object.class);
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
and with:
private JsonNode get3rdJsonAsNode() {
objectMapper = new ObjectMapper();//.enable(SerializationFeature.INDENT_OUTPUT);
JsonNode json = null;
try {
json = objectMapper.readTree(new File(this.mono3rdJsonPath));
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
I am writing with this:
private void writeProvisionAsObject(Object json) {
ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
String updatedJsonString;
try {
updatedJsonString = writer.writeValueAsString(json);
// Write the updated JSON string back to the JSON file
objectMapper.writeValue(new File(this.filePath), updatedJsonString);
} catch (IOException e) {
e.printStackTrace();
}
}
Also I’ve heard of JsonTokenizer but I’ve read that in order to preserve original formatting, I must append each line manually, which I am trying to avoid.
How can I achieve preserving orginal formating?
2
Answers
You won’t be able to this with Jackson. Jackson’s purpose to serialize/deserialize from/to objects and necessarily "formatting" is lost.
I recommend you look at a library like Streamflyer allows you to modify a JSON stream by matching on a Regex and replacing matches as the stream passes through the processor.
Jackson knows about JsonLocation. A parser keeps track of which content is being parsed at which location. You could use this information to restore a lot of formatting like whitespace at start of lines or even whitespace between array elements.
But extending this to also preserve line breaks (when needing to differentiate between line windows and linux line breaks for example) needs extensive customization in the parser and possibly
JsonLocation
too. This might be possible but its questionalbe if its worth the effort.