问题
I have a Spring Web Application working with the 4.3.6
version. It works with XML and JSON until some point.
- For Json I use Jackson.
- For XML I used to work with
JAXB2
, but not anymore because it does not support Generic collections
A Generic collection is represented such as:
public class GenericCollection<T> {
private Collection<T> collection;
public GenericCollection(){
this.collection = new LinkedHashSet<>();
}
public GenericCollection(Collection<T> collection){
this.collection = collection;
}
...
Thus for XML
the application moved from JABX2
to Jackson
working with the jackson-dataformat-xml project
To serialize a Date
for JSON I use:
public class JsonDateSerializer extends JsonSerializer<Date> {
private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
/**
* {@inheritDoc}
*/
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers)
throws IOException, JsonProcessingException {
String formattedDate = dateFormat.format(value);
gen.writeString(formattedDate);
}
}
And used how:
@JsonProperty("fecha")
@JsonSerialize(using=JsonDateSerializer.class)
public Date getFecha() {
return fecha;
}
For XML, when JAXB2
was used, again for Date
serialization the following was used:
public class XmlDateAdapter extends XmlAdapter<String, Date> {
private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
/**
* {@inheritDoc}
*/
@Override
public Date unmarshal(String v) throws Exception {
return dateFormat.parse(v);
}
/**
* {@inheritDoc}
*/
@Override
public String marshal(Date v) throws Exception {
return dateFormat.format(v);
}
}
And used how:
@JsonProperty("fecha")
@JsonSerialize(using=JsonDateSerializer.class)
@XmlElement(name="fecha")
@XmlJavaTypeAdapter(XmlDateAdapter.class)
public Date getFecha() {
return fecha;
}
Due this migration from Jaxb2
to jackson-dataformat-xml
I know that the latter ignores the JAXB2
annotations. Thus working now with:
@JsonProperty("fecha")
@JsonSerialize(using=JsonDateSerializer.class)
@JacksonXmlProperty(localName="fecha")
@XmlJavaTypeAdapter(XmlDateAdapter.class)
public Date getFecha() {
return fecha;
}
Therefore from @XmlElement(name="fecha")
to @JacksonXmlProperty(localName="fecha")
The problem now is the that @XmlJavaTypeAdapter(XmlDateAdapter.class)
is ignored too.
Question:
What is the equivalent annotation of @XmlJavaTypeAdapter
from JAXB2
to jackson-dataformat-xml
来源:https://stackoverflow.com/questions/42682955/for-date-serialization-what-is-the-equivalent-annotation-of-xmljavatypeadapter