クイック イントロ (スキップできます) : こんにちは、このトピックについては多くの質問と回答がありますが、解決策が非常に単純で、考えもしない場合があります。すべての回答に補足を投稿します。
問題 : POST 要求を処理して JSON オブジェクトを保存する JSON REST サービスがありますが、そのオブジェクトには、Genson によってそのままでは解析されない Date フィールドが含まれています。
Java オブジェクト:
public class MyObj {
// The field you want to serialize/deserialize
private Date date;
// Constructor with no arguments needed by Genson
public MyObj() {}
}
Jersey を使用した REST サービス:
@Path("/api/my-obj")
public class MyObjAPI {
@POST
@Consumes("application/json")
public Response insert(MyObj myObj) {
// do what you want with myObj, it's ready to use with the date
return Response.created('url/to/created/object').build();
}
}
jQuery を使用した JavaScript のクライアント:
// This is the JSON Object to POST
var myObj = {
date: new Date()
};
$.ajax({
method: 'POST',
url: '/api/my-obj',
data: JSON.stringify(myObj),
dataType: 'json',
processData: false,
contentType: 'application/json'
});