Jackson can use custom serializer where you can have control in generating the output.
The following are the step to do this:
Annotate your POJO to use a custom serializer
@JsonSerialize(using = CustomSerializer.class)
static class User{
public Long id;
public String firstName;
public User(Long id, String firstName) {
this.id = id;
this.firstName = firstName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
Declare the serialzer
static class CustomSerializer extends JsonSerializer{
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider serializers) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeArrayFieldStart("inputFields");
Field[] fields = value.getClass().getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
jgen.writeStartObject();
jgen.writeObjectField("name", field.getName());
jgen.writeObjectField("value", field.get(value));
jgen.writeEndObject();
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
jgen.writeEndArray();
jgen.writeEndObject();
}
}
A simple test
public static void main(String[] args) throws JsonProcessingException {
User user = new User(1L, "Mike");
ObjectMapper om = new ObjectMapper();
om.writeValueAsString(user);
System.out.println(om.writeValueAsString(user));
}
And the output will be
{"inputFields":[{"name":"id","value":1},{"name":"firstName","value":"Mike"}]}