英文:
OffsetDateTime invalid format
问题
我尝试提取包含ZoneDateTime值的字符串。
ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()).disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String date = "2019-06-12T22:00:00-04:00";
OffsetDateTime odt = objectMapper.readValue(date, OffsetDateTime.class);
System.out.println(odt);
Jackson报错:parserException: 出现意外字符 -
这个命令是有效的
OffsetDateTime.parse("2019-06-12T22:00:00-04:00");
因此看起来是Jackson的问题。
英文:
I try to take a string who contain a vlaue of zoneDateTime.
ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()).disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String date = "2019-06-12T22:00:00-04:00";
OffsetDateTime odt = objectMapper.readValue(date, OffsetDateTime.class);
System.out.println(odt);
Jackson said: parserException: unexpected character -
This command is valid
OffsetDateTime.parse("2019-06-12T22:00:00-04:00");
So seem like a jackson issue
答案1
得分: 1
objectMapper.readValue(date, OffsetDateTime.class)
期望字符串 date
为有效的 JSON。
因此,使用这种方法的一种方式是从以下示例开始:
String json = "{\"odt\": \"2019-06-12T22:00:00-04:00\"}";
然后创建一个对象来存储这个 JSON,例如:
import java.time.OffsetDateTime;
public class ODT {
private OffsetDateTime odt;
public OffsetDateTime getOdt() {
return odt;
}
public void setOdt(OffsetDateTime odt) {
this.odt = odt;
}
}
现在,以下代码将使用你的对象映射器成功处理输入:
ODT myOdt = objectMapper.readValue(json, ODT.class);
System.out.println(myOdt.getOdt());
这将打印:
2019-06-13T02:00Z
更新
要使用原始偏移量而不是 UTC 来显示此值,你可以使用以下代码:
System.out.println(myOdt.getOdt().atZoneSameInstant(ZoneId.of("-04:00")));
这将打印:
2019-06-12T22:00-04:00
这与我们起始的 JSON 字符串中的原始值相同。
英文:
The objectMapper.readValue(date, OffsetDateTime.class)
expects the string date
to be valid JSON.
So, one way to use this would be to start with an example such as the following:
String json = "{ \"odt\" : \"2019-06-12T22:00:00-04:00\" }";
And then create an object to store this JSON, for example:
import java.time.OffsetDateTime;
public class ODT {
private OffsetDateTime odt;
public OffsetDateTime getOdt() {
return odt;
}
public void setOdt(OffsetDateTime odt) {
this.odt = odt;
}
}
Now, the following code will handle the input successfully, using your object mapper:
ODT myOdt = objectMapper.readValue(json, ODT.class);
System.out.println(myOdt.getOdt());
This prints:
2019-06-13T02:00Z
Update
To display this value using the original offset, instead of UTC, you can use the following:
System.out.println(myOdt.getOdt().atZoneSameInstant(ZoneId.of("-04:00")));
This prints:
2019-06-12T22:00-04:00
This is the same as the original value in our starting JSON string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论