[英]@XmlJavaTypeAdapter doesn't work
我收到了該錯誤http://jira.codehaus.org/browse/JACKSON-288 ,但是它說該錯誤應該已經在1.6.2版中修復。
我指的是很多線程,例如,
澤西島JSON和日期
如何通過XML將Date(ActionScript 3)轉換為java.util.Date?
我嘗試了1.12、1.14、1.17.1版,但都無法在我這邊工作。
@XmlRootElement(name="info")
@XmlAccessorType(XmlAccessType.NONE)
public class InfoVO {
private int infoId;
@XmlElement
@XmlJavaTypeAdapter(DateAdapter.class)
private Date createTime;
//...get/set
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.ws.rs.WebApplicationException;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class DateAdapter extends XmlAdapter<String, Date> {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public String marshal(Date v) {
return dateFormat.format(v);
}
@Override
public Date unmarshal(String v) {
try {
return dateFormat.parse(v);
} catch (ParseException e) {
throw new WebApplicationException();
}
}
}
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
但是根本無法調用DateAdapter並出現異常,
2013-06-12 11:11:13.363:WARN :: // xa / info / save / 12121:org.codehaus.jackson.map.JsonMappingException:無法從字符串值'2013-06構造java.util.Date實例-08 08:00:00':不是有效的表示形式(錯誤:無法解析日期“ 2013-06-08 08:00:00”:與任何標准格式都不兼容(“ yyyy-MM-dd'T' HH:mm:ss.SSSZ“,” yyyy-MM-dd'T'HH:mm:ss.SSS'Z'“,” EEE,dd MMM yyyy HH:mm:ss zzz“,” yyyy-MM-dd “))| 在[來源:java.io.StringReader@b0ff5e1; 第8行,第23列)(通過參考鏈:com.xchange.me.vo.InfoVO [“ createTime”])
我找到了根本原因,因為我添加了自定義的MessageBodyReader,
@Provider
@Consumes("application/json")
public class CustomJsonReader<T> implements MessageBodyReader<T> {
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return true;
}
@Override
public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException {
/*
* Copy the input stream to String. Do this however you like. Here I use
* Commons IOUtils.
*/
StringWriter writer = new StringWriter();
IOUtils.copy(entityStream, writer, "UTF-8");
String json = writer.toString();
/*
* if the input stream is expected to be deserialized into a String,
* then just cast it
*/
if (String.class == genericType)
return type.cast(json);
/*
* Otherwise, deserialize the JSON into a POJO type. You can use
* whatever JSON library you want, here's a simply example using GSON.
*/
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, type);
}
}
因此,當接收到json數據時,總是進入readFrom方法,然后在該行中引發異常return objectMapper.readValue(json,type);
所以我認為根本原因是ObjectMapper.readValue忽略注釋@XmlJavaTypeAdapter
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.