gpt4 book ai didi

java - 序列化 Joda DateTime 对象根据上下文创建不同的输出

转载 作者:行者123 更新时间:2023-11-30 10:00:43 25 4
gpt4 key购买 nike

我有一个对象,其中嵌套了一个 Joda DateTime 对象,但我在对其进行序列化和反序列化时遇到了问题。

当我序列化 DateTime 嵌套的完整对象时,输出看起来与我直接序列化 DateTime 对象时大不相同,我的结果如下

new ObjectMapper.writeValueAsString(fullObjectWithDateTime) 为 DateTime 对象生成以下 blob:

{
"dateTime": {
"weekOfWeekyear": 34,
"weekyear": 2019,
"yearOfEra": 2019,
"yearOfCentury": 19,
"centuryOfEra": 20,
"secondOfDay": 4530,
"minuteOfDay": 75,
"millisOfDay": 4530777,
"monthOfYear": 8,
"hourOfDay": 1,
"minuteOfHour": 15,
"secondOfMinute": 30,
"millisOfSecond": 777,
"year": 2019,
"dayOfMonth": 21,
"dayOfWeek": 3,
"era": 1,
"dayOfYear": 233,
"millis": 1566350130777,
"chronology": {
"zone": {
"fixed": true,
"id": "UTC"
}
},
"zone": {
"fixed": true,
"id": "UTC"
},
"afterNow": false,
"beforeNow": true,
"equalNow": false
}
}

ObjectMapper.writeValueAsString(fullObjectWithDateTime.getDateTime())

产生:

"2019-08-21T01:15:30.777Z"

当我尝试反序列化由 ObjectMapper.writeValueAsString(fullObjectWithDateTime) 生成的对象时出现错误,它说

'com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of org.joda.time.DateTime out of START_OBJECT token'

最佳答案

您需要注册JodaModule .

例子:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import org.joda.time.DateTime;

public class JsonApp {

public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.registerModule(new JodaModule());

String json = mapper.writeValueAsString(new MyModel());
System.out.println(json);
MyModel model = mapper.readValue(json, MyModel.class);
System.out.println(model);
}
}

class MyModel {
private DateTime now = DateTime.now();

public DateTime getNow() {
return now;
}

public void setNow(DateTime now) {
this.now = now;
}

@Override
public String toString() {
return "MyModel{" +
"now=" + now +
'}';
}
}

以上代码打印:

{"now":"2019-09-06T21:58:34.917Z"}
MyModel{now=2019-09-06T21:58:34.917Z}

关于java - 序列化 Joda DateTime 对象根据上下文创建不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57824754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com