3 回答
TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊
我認(rèn)為你工作太努力了,沒(méi)有得到你想要的。有一種更簡(jiǎn)單的方法,無(wú)需編寫(xiě)自己的反序列化器??纯催@個(gè)問(wèn)題。本質(zhì)上它看起來(lái)像
@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="EEE MMM dd HH:mm:ss Z yyyy")
@JsonProperty("created_at")
ZonedDateTime created_at;
而你只是戴上你自己的面具。另外,我曾經(jīng)有一個(gè)任務(wù)是解析未知格式的日期,本質(zhì)上我需要解析任何有效的日期。這是一篇描述如何實(shí)現(xiàn)它的想法的文章:Java 8 java.time package: parsing any string to date。你可能會(huì)發(fā)現(xiàn)它很有用
TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個(gè)贊
不是在使用活頁(yè)夾庫(kù)時(shí)(綁定的關(guān)鍵在于它不是動(dòng)態(tài)的。)。
但是你可以在使用簡(jiǎn)單的解析庫(kù)時(shí),比如 org.json
TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超4個(gè)贊
當(dāng)您使用java.time.*類(lèi)并且Jackson最好從JavaTimeModule來(lái)自jackson-datatype-jsr310模塊的注冊(cè)開(kāi)始。我們可以擴(kuò)展它并使用提供的模式注冊(cè)序列化程序,如下例所示:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class JsonApp {
public static void main(String[] args) throws Exception {
ObjectMapper mapperIso = createObjectMapper("yyyy-MM-dd");
ObjectMapper mapperCustom0 = createObjectMapper("yyyy/MM/dd");
ObjectMapper mapperCustom1 = createObjectMapper("MM-dd-yyyy");
System.out.println(mapperIso.writeValueAsString(new Time()));
System.out.println(mapperCustom0.writeValueAsString(new Time()));
System.out.println(mapperCustom1.writeValueAsString(new Time()));
}
private static ObjectMapper createObjectMapper(String pattern) {
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(pattern)));
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(javaTimeModule);
return mapper;
}
}
class Time {
private LocalDate now = LocalDate.now();
public LocalDate getNow() {
return now;
}
public void setNow(LocalDate now) {
this.now = now;
}
@Override
public String toString() {
return "Time{" +
"now=" + now +
'}';
}
}
Aboce 代碼打?。?/p>
{"now":"2019-02-24"}
{"now":"2019/02/24"}
{"now":"02-24-2019"}
添加回答
舉報(bào)
