I’m having json type in my Postgres DB and getting it as POJO
.
Then I’m trying to write my POJO
to String
.
POJO
is being populated correctly, but when Jackson writes it to String
, I get {"traversableAgain" : true, "empty" : false}
for nested JSON
whose type in POJO
is Object
.
My POJO
:
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyClass {
private String property1;
private Double property2;
private Boolean property3;
private Object problematicProperty;
}
JSON I’m retrieving from DB:
{
"property1" : "randomString",
"property2" : 0.3,
"property3" : false,
"problematicProperty" : {
"yearFromDate": [
"dob",
"yyyyMMdd"
]
}
}
My code:
MyClass myPOJO = myRepository.getOne(pojoID);
ObjectMapper obj = getObjectMapper();
obj.enable(SerializationFeature.INDENT_OUTPUT);
obj.enable(SerializationFeature.WRAP_ROOT_VALUE);
String stringLayout = obj
.writerWithDefaultPrettyPrinter()
.writeValueAsString(myPOJO);
When I print stringLayout, I get:
{
"property1" : "randomString",
"property2" : 0.3,
"property3" : false,
"problematicProperty" : {"traversableAgain" : true, "empty" : false}
}
instead of
{
"property1" : "randomString",
"property2" : 0.3,
"property3" : false,
"problematicProperty" : {
"yearFromDate": [
"dob",
"yyyyMMdd"
]
}
}
I used java.lang.Object type because problematicProperty is "dynamic", sometimes it will be nested json like above, and sometimes string e.g. like this:
"problematicProperty" : "randomText"
When testing, if I use com.fasterxml.jackson.databind.node.ObjectNode
type instead of Object
, string is properly being written. But I can’t use ObjectNode
with Hibernate.
Why is this happening and is there a way to configure objectMapper
to write java.lang.Object
(that is actually a nested JSON
) to String
properly?
2
Answers
Inspired by this answer and this link I added
And now it works fine and code looks like this:
A complete example would help here. If I create a dummy example from your code – see below, then it works as expected.
The
{"traversableAgain" : true, "empty" : false}
JSON is coming from what is most likely a Scala type, probably a Scala Map. It’s difficult to say how to fix it without seeing where this data is coming from. One possible solution might be to change the problematicProperty field type to a (Java) Map, and convert the Scala Map when the object is constructed.