だから、あなたが日付フィールドbirthdate
を持ってData
というプロパティを持っている持っているUser
と呼ばれるクラスを持っている、とあなたは、標準の日付デシリアライザを使用すると、カスタム1を使用したいと考えていないと言うことができます。以下はその達成方法です。
User.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
@JsonProperty("code")
public Integer code;
@JsonProperty("status")
public String status;
@JsonProperty("message")
public String message;
@JsonProperty("time")
public String time;
@JsonProperty("data")
public Data data;
}
Data.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Data {
@JsonProperty("id_hash")
public Integer idHash;
@JsonProperty("user_name")
public String userName;
@JsonProperty("user_surname")
public String userSurname;
@JsonProperty("birthdate")
@JsonDeserialize(using = BirthdayDeserializer.class)
public Date birthdate;
@JsonProperty("height")
public Integer height;
@JsonProperty("weight")
public Integer weight;
@JsonProperty("sex")
public Integer sex;
@JsonProperty("photo_path")
public String photoPath;
}
BirthdayDeserializer.java
public class BirthdayDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = jsonparser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
Main.javaでテストします。
public class Main {
public static void main(String[] args) throws IOException {
String json = "{\n" +
" \"code\": 1012,\n" +
" \"status\": \"sucess\",\n" +
" \"message\": \"Datos Del Usuario\",\n" +
" \"time\": \"28-10-2015 10:42:04\",\n" +
" \"data\": {\n" +
" \"id_hash\": 977417640,\n" +
" \"user_name\": \"Daniel\",\n" +
" \"user_surname\": \"Hdz Iglesias\",\n" +
" \"birthdate\": \"1990-02-07\",\n" +
" \"height\": 190,\n" +
" \"weight\": 80,\n" +
" \"sex\": 2\n" +
" }\n" +
"}";
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Date.class, new BirthdayDeserializer());
mapper.registerModule(module);
User readValue = mapper.readValue(json, User.class);
System.out.println(readValue);
}
}
私はカスタムDeserializer
を登録しているかのようにmainメソッドを確認してください。
私が尋ねたものとまったく同じものではありません。あなたの例では、新しいSimpleDateFormat( "yyyy-MM-dd HH:mm:ss")を使用する代わりに、新しいSimpleDateFormat(myDateFormat)などの日付書式をパラメータにしたいとします。デシリアライザにパラメータmyDateFormatを渡すにはどうすればよいですか? –
あなたのスキーマは変更されますか?もしそうでなければ、それは上記の日に行ったようにそれをすることはできませんか?私はそれをハードコーディングするか、またはそれをいくつかのファイルから読むことを意味しますか? –
いいえ、スキーマは状況によって異なります。それはデータベーステーブルのようなものです。ユーザーはコードを構成する際にスキーマを定義します。スキーマはオブジェクト内のフィールドに保持されます。 –