Access field annotation from custom serializer

Viewed 2128

I am working with a legacy system where the data is essentially saved in a de-normalized format. To make matters worse, there is no consistent naming convention used. Take the object below, which essentially contains two addresses (but could be more):

{
   "studentAddress": "123 new Street",
   "studentCity": "New City",
   "studentState_w": "NY",
   "studentZip": "11220",
   "teacherAddress:: "424 main st",
   "teacherCity_txt": "Summerville",
   "teacherState_x" : "NJ",
   "teacherZip": "13454",
   ...
   ...
}

I would like to serialize/deserialize from/to the following object:

public class SomeData {    
    Address teacher;
    Address student;

    public static class Address {
       String address;
       String city;
       String state;
       String zipcode;
    }
}

My idea is to create a custom annotation AddressMapper like this:

public @interface AddressMapper {
    String addressField () default "address",
    String cityField () default "city",
    String stateField () default "state",
    String zipField () default "zipcode"
} 

Then use it on the class like this:

public class SomeData {
    @AddressMapper (addressField="teacherAddress", cityField="teacherCity_txt", stateField="studentState_w", zipField="teacherZip")    
    @JsonSerialize(using = AddressSerializer.class)
    Address teacher;
    @AddressMapper (addressField="studentAddress", cityField="studentCity", stateField="studentState_w", zipField="studentZip")   
    @JsonSerialize(using = AddressSerializer.class)
    Address student; 
}

However, I couldn't find a way to get a hold of @AddressMapper annotation from the serialize method

public class AddressMapper extends JsonSerializer<Address> {
    public void serialize(Address value, JsonGenerator jgen, SerializerProvider provider) {
        //How to i get field annotation????
    }
}

How can I get the instance of field annotation here? Is there another way I should approach this problem?

2 Answers
Related