我有使用Jersey的Glassfish服务器用于webservices。 我在身体中发送带有JSON的POST请求,并希望Jackson将其映射到JPA实体。 那是NPE出现的时候。
实体:
@Entity
@XmlRootElement
@Table(name = "tracks", schema = "public", catalog = "xtracker")
public class Track {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "track_id", nullable = false, insertable = true, updatable = true)
private Long trackId;
@Basic
@Column(name = "time_start", nullable = true, insertable = true, updatable = true)
private Timestamp timeStart;
@Basic
@Column(name = "time_end", nullable = true, insertable = true, updatable = true)
private Timestamp timeEnd;
@OneToMany(mappedBy = "track")
private List<Jump> jumps = new ArrayList<>();
@OneToMany(mappedBy = "track", cascade = CascadeType.PERSIST)
private List<Point> points = new ArrayList<>();
@ManyToOne
@JoinColumn(name = "user_id", referencedColumnName = "user_id")
private User user;
...getters and setters
REST方法:
@POST
@Path("tracks")
@Produces("application/json")
@Consumes(MediaType.APPLICATION_JSON)
@Secured
public void addTrack(Track track) {
System.out.println("track" + track.getTrackId());
}
异常指向track.getTrackId()
杰克逊正常工作,因为当我尝试使用一个字段(没有ManyToOne关系)映射简单的Test对象时,它是正常的
ApplicationConfig:
@javax.ws.rs.ApplicationPath("api")
public class ApplicationConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
// following code can be used to customize Jersey 2.0 JSON provider:
try {
Class jsonProvider = Class.forName("org.glassfish.jersey.jackson.JacksonFeature");
// Class jsonProvider = Class.forName("org.glassfish.jersey.moxy.json.MoxyJsonFeature");
// Class jsonProvider = Class.forName("org.glassfish.jersey.jettison.JettisonFeature");
resources.add(jsonProvider);
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
resources.add(SecurityFilter.class);
addRestResourceClasses(resources);
return resources;
}
/**
* Do not modify addRestResourceClasses() method.
* It is automatically re-generated by NetBeans REST support to populate
* given list with all resources defined in the project.
*/
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(RestResource.class);
}
}
更新 这是来自客户端的JSON示例(我检查它确实到达了泽西岛):
{"jumps":[],"points":[{"pointId":0,"speed":0.2}]}
(pointId和speed是Point字段)
更新2: 问题解决了:RequestFilter正在清除http实体主体,而null实体正在到达该方法。谢谢!