我正在尝试让服务器解析以下JSON:
{"hardwareId":1,"registerTime":"2017-02-14T03:42:11.482Z","sensorId":1,"temperature":23.6}
registerTime
属性必须解析为OffsetDateTime
实例:@XmlRootElement
public class TemperatureRegister {
private int m_hardwareId;
private int m_sensorId;
private OffsetDateTime m_registerTime;
private double m_temperature;
public TemperatureRegister() {
}
public TemperatureRegister(OffsetDateTime p_registerTime, double p_temperature,
int p_hardwareId, int p_sensorId) {
if (p_registerTime == null) {
this.m_registerTime = OffsetDateTime.now(ZoneOffset.UTC);
}
this.m_registerTime = p_registerTime;
this.m_temperature = p_temperature;
this.m_hardwareId = p_hardwareId;
this.m_sensorId = p_sensorId;
}
...
}
这就是我的资源方法的定义方式:
@POST
@Path("/insert")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public TemperatureRegister addOne(TemperatureRegister p_register) {
m_mongoConnector.InsertOne(p_register);
return p_register;
}
由于某种原因,在上述方法中,
p_register
参数始终像这样:TemperatureRegister [m_hardwareId=1, m_sensorId=1, m_registerTime=null, m_temperature=23.6]
它会正确映射所有内容,但
registerTime
是OffsetDateTime
。总是null
。为什么这是唯一有问题的价值?难道我做错了什么?是否需要一些特殊的配置来处理OffsetDateTime`?
最佳答案
如果您使用Jackson作为JSON提供程序,则需要jackson-datatype-jsr310
依赖项来支持OffsetDateTime
:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.8.6</version>
</dependency>
当您的类字段名称与JSON属性名称不匹配时,您还想用
TemperatureRegister
注释@JsonProperty
字段:public class TemperatureRegister {
@JsonProperty("hardwareId")
private int m_hardwareId;
@JsonProperty("sensorId")
private int m_sensorId;
@JsonProperty("registerTime")
private OffsetDateTime m_registerTime;
@JsonProperty("temperature")
private double m_temperature;
// Constructor, getters and setters omitted
}
关于java - 在新泽西消费OffsetDateTime,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42218269/