Search code examples
javamavenstruts2convertersstruts2-json-plugin

Custom Struts type converter is not working


I do have a getter/setter for the Date variable, like so:

private Date registrationDate;

@TypeConversion(converter = "org.com.helper.DataHelper")
public Date getRegistrationDate() {
    return registrationDate;
}

@TypeConversion(converter = "org.com.helper.DataHelper")
public void setRegistrationDate(Date registrationDate) {
    this.registrationDate = registrationDate;
}

As you can see I've created a custom struts converter to convert the incoming string to the Date format and then assign it. But it doesn't seem to work. Here is the code for DateHelper:

public class DateHelper extends StrutsTypeConverter {

    private static final DateFormat FORMAT = new SimpleDateFormat("dd-MM-yyyy");

    @Override
    public Object convertFromString(Map arg0, String[] values, Class arg2) {
           try {
               System.out.println(values[0]+"called from datahelper");

                return FORMAT.parse(values[0]);
            } catch (Exception e) {
                throw new TypeConversionException(e.getMessage());
            }
    }

    @Override
    public String convertToString(Map arg0, Object value) {
        try {
            return FORMAT.format(value);
        } catch (Exception e) {
            throw new TypeConversionException(e.getMessage());
        }
    }

}

I use struts2-json plugin to get and parse the form data. This plugin does assign automatically all string values but I do have an issue with the Date.

This is how I get the data passed to Java from the form.

{"data":{"recordId":"123","registrationDate":"20-07-2016","hisId":"","herId":"","lastNameHe":"Asd","firstNameHe":"Asd","middleNameHe":"Asd","workPlaceHe":"","educationHe"}}

So, according to my understanding the code before starting to set the registrationDate should call the helper class and convert the string to date and then call the registrationDate setter.. but it doesn't seem to work.. I've even put a log call in the helper code but it doesn't show up in the eclipse.


Solution

  • Seems like struts2-json-plugin doesn't use default type conversions. :(

    For setting date format you can use @JSON annotation which has format property.

    @JSON(format = "dd.MM.yyyy")
    public void setRegistrationDate(Date registrationDate) {
        this.registrationDate = registrationDate;
    }
    

    JSON plugin documentation - Customizing Serialization and Deserialization.