This is the sample code what I am doing to log the JSON object to the console and including error stack trace as part of field2. While I log to the console, that is not readable.
Sample Code to understand issue.
package goal.test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestClass {
String field1 = "hello";
String field2 = "hi\r\ntest";
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
public String getField2() {
return field2;
}
public void setField2(String field2) {
this.field2 = field2;
}
public static void main(String[] args) throws JsonProcessingException {
whatIsPossibleNow();
whatINeed();
}
static void whatIsPossibleNow() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(new TestClass());
System.out.println(result);
/**
* output
* {
* "field1" : "hello",
* "field2" : "hi\r\ntest"
* }
*/
}
static void whatINeed() throws JsonProcessingException {
TestClass obj = new TestClass();
/**
*
* field2 also need to formatted while printing
* expected output
* {
* "field1" : "hello",
* "field2" : "hi
* test"
* }
* output of the field2 should be something this what this prints
*/
System.out.println(obj.getField2());
}
static void howCouldBe() throws JsonProcessingException {
/**
* how to achieve this now ??
*/
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValueAsString(new TestClass()).prettyPrint();
}
}
I am confused if there is any other way achieving as I need to pretty print object while deserializing.