I have a POJO like this:
public class Person {
public long id;
public String someOtherId;
public String vollName;
public int alter;
}
I am converting the POJO to JSON using the mixin:
@JsonIncludeProperties( { "id", "name", "age", "customFields" } )
abstract class PersonM extends Person {
@JsonProperty( "id" ) String someOtherId;
@JsonProperty( "name" ) String vollName;
@JsonProperty( "age" ) String alter;
}
...
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn( Person.class, PersonM.class );
String body = mapper.writeValueAsString( person );
The code works like charm and produces a JSON of:
{
"id": "xxxxxx",
"name": "Aaaa Bbbb",
"age": 111
}
Now I need to extend the JSON to contain a customFields
element:
{
"id": "xxxxxx",
"name": "Aaaa Bbbb",
"age": 111,
"customFields": {
"originalId": 333333
}
}
so that the content of that new element is based on other fields of the same POJO, and would look like so as a getter:
public class Person {
...
public Map getCustomFields() { return Map.of( "originalId", id ); }
}
I don’t want to include this or similar methods into my POJO for a number of reasons and would like to do it on StdSerializer<>
-level.
On the Internet I could not find any example on adding another JSON element to the existing fields, all samples show building JSON from scratch instead.
Hence the question: How to add a JSON Object to existing output without "re-inventing the wheel" over and over again?
2
Answers
create a custom PersonDeserializer by extending JsonDeserializer. Inside the deserialize method, we extract the id, name, and age values from the JSON node. Then, we create a Person object and set its properties accordingly. Additionally, we create a customFields map and populate it with the desired custom field values. Finally, we set the customFields map on the Person object.
To use this custom deserializer, you need to register it with the ObjectMapper:
or try this :
You can add elements to your json, your only need convert from String, did you try this?