-
Notifications
You must be signed in to change notification settings - Fork 0
Converters
Most of the data read from JSON and XML is converted to the fields type using specific converters. When serializing POJOs to JSON / XML these converters are used to convert from the fields type to string. Therefore Piriti uses the following converters:
- boolean / Boolean → !BooleanConverter
- byte / Byte → !ByteConverter
- char / Character → !CharacterConverter
- double / Double → !DoubleConverter
- float / Float → !FloatConverter
- int / Integer → !IntegerConverter
- long / Long → !LongConverter
- short / Short → !ShortConverter
- java.util.Date → !DateConverter
- java.sql.Date → !SqlDateConverter
- java.sql.Time → !TimeConverter
- java.sql.Timestamp → !TimestampConverter
All converters implement the Converter interface:
public interface Converter
{
/**
* Converts the specified value to the type T.
*
* @param value
* The string to be converted. May be null
.
* @return The converted type or null
if a conversion is not
* possible
*/
T convert(String value);
/**
* Serializes the specified value to a string.
*
* @param value
* The value to serialize. May be <code>null</code>.
* @return The serialized string or <code>null</code> if no value was given.
*/
String serialize(T value);
}
You can customize the built-in converters or write your own: public class BackAndForth { // reader @Format("dd.MM.yy") Date date; @Convert(DurationConverter.class) int duration; }
public class DurationConverter extends AbstractConverter<Integer>
{
@Override
public Integer convert(String value)
{
if (isValid(value))
{
return Integer.valueOf(value.substring(0, value.length() - 1));
}
return 0;
}
@Override
public String serialize(Integer value)
{
return value + "h";
}
}
The example uses the @Format annotation so customize the built-in !DateConverter and specifies a custom converter for the duration. Here is the relevant JSON data: { "date": "20.09.04", "duration": "4h" }
For some built-in converters you can specify a custom format using the @Format annotation:
- !DoubleConverter
- !FloatConverter
- !IntegerConverter
- !LongConverter
- !DateConverter
If you want to use a format for your custom converter you have to provide a constructor which takes the format string. The easiest way to do this is to extend from !FormatableConverter<T
>:
public abstract class FormatableConverter extends AbstractConverter
{
private final String format;
public FormatableConverter(String format)
{
this.format = format;
}
public String getFormat()
{
return format;
}
}