我试图让我的服务器解析以下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`?
答案 0 :(得分:2)
如果您使用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属性名称不匹配时,您还希望使用@JsonProperty
对TemperatureRegister
字段进行注释:
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
}