Search code examples
jsonspringspring-bootjackson-databind

JSON conversion to a specific format


I have a Java Object and trying to convert this to a specific JSON format

    public class Audit {
       String auditId;
       String auditData;
    }

and above object needs to convert to below JSON format

{
    "event":"auditId=100,auditData=purchase order"
}

how do we convert above format using Jackson parser


Solution

  • You need to write a custom serializer for Audit class.

    public class AuditSerializer extends StdSerializer<Audit> {
    
        public AuditSerializer() {
            super(Audit.class);
        }
    
        protected AuditSerializer(Class<Audit> auditClass) {
            super(auditClass);
        }
    
        @Override
        public void serialize(Audit audit, JsonGenerator gen, SerializerProvider provider) throws IOException {
            gen.writeStartObject();
            String key = "event";
            String value = String.format("auditId=%s,auditData=%s", audit.auditId, audit.auditData);
            gen.writeStringField(key, value);
            gen.writeEndObject();   
        }
    }
    

    And then use this custom serializer to get JSON string for Audit:

    SimpleModule module = new SimpleModule();
    module.addSerializer(new AuditSerializer(Audit.class));
    
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(module);
    
    Audit audit = new Audit();
    audit.auditId = "100";
    audit.auditData = "purchase Order";
    System.out.println(mapper.writeValueAsString(audit));
    // {"event":"auditId=100,auditData=purchase Order"}
    

    If you annotate Audit class with @JsonSerialize(using=AuditSerializer.class), then you do not need to explicitly register AuditSerializer.

    @JsonSerialize(using=AuditSerializer.class)
    public class Audit {
        ...
    

    And you use ObjectMapper directly.

    Audit audit = new Audit();
    audit.auditId = "100";
    audit.auditData = "purchase Order";
    
    ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(audit));
    // {"event":"auditId=100,auditData=purchase Order"}