我在尝试制作REST服务时遇到问题。我使用内置的GlassFish 4.1和Jersay 2.1。
@Path("/driver")
@RequestScoped
public class DriverResource {
private static Logger logger = LogManager.getLogger(DriverResource.class);
@Inject
private DriverManager driverManager;
private SharedResponseFactory responseFactory = new SharedResponseFactory();
@GET
@Path("/login/{pesel}/{password}")
@Produces("application/json")
public Response logIn(@PathParam("pesel") String pesel, @PathParam("password") String password) {
try {
Driver driver = driverManager.logIn(pesel, password);
logger.debug("Zalogowano kierowcę: " + driver.getFullName());
return responseFactory.getSuccesResponse(driver);
} catch (ErrorDAOException e) {
logger.catching(e);
return responseFactory.getFailureResponse(e);
} catch (NoDataFoundDAOException e) {
logger.catching(e);
return responseFactory.getFailureResponse(e);
} catch (Exception e) {
logger.catching(e);
return responseFactory.getFailureResponse(e);
}
}
}
当我试图返回我的实体时,我会得到这样的回复:
{}
在我的实体中有许多循环引用,我不会在实际实现上操作但是接口。我需要按照我的Android应用程序中的Retrofit进行反序列化的方式。
Glassfish的日志是空的,没有与休息有关的错误。我不知道如何让它发挥作用。
我尝试使用@JsonIdentityInfo
来处理循环引用和@JsonTypeInfo
以使接口可以反序列化。
我认为有一个小技巧会让它发挥作用,但不幸的是我不知道......
答案 0 :(得分:1)
我找到了一种测试循环引用的相对简单的方法。如果您使用JAXB(包含在glassfish中),您可以尝试将实体编组为XML。如果找到任何循环引用,则抛出JAXBException。
这是一种将对象编组为XML的方法:
public static <T> String marshalToXml(T instance) throws javax.xml.bind.JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(instance.getClass());
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
jaxbMarshaller.marshal(instance, writer);
return writer.toString();
}
并且服务可以像这样测试对象:
@Path("/driver")
@RequestScoped
public class DriverResource {
private static Logger logger = LogManager.getLogger(DriverResource.class);
@Inject
private DriverManager driverManager;
private SharedResponseFactory responseFactory = new SharedResponseFactory();
@GET
@Path("/login/{pesel}/{password}")
@Produces("application/json")
public Response logIn(@PathParam("pesel") String pesel, @PathParam("password") String password) {
try {
Driver driver = driverManager.logIn(pesel, password);
marshalToXml(driver); //remember to import static method
logger.debug("Zalogowano kierowcę: " + driver.getFullName());
return responseFactory.getSuccesResponse(driver);
} catch (ErrorDAOException e) {
logger.catching(e);
return responseFactory.getFailureResponse(e);
} catch (NoDataFoundDAOException e) {
logger.catching(e);
return responseFactory.getFailureResponse(e);
} catch (JAXBException e) {
//view error message to see cyclic reference
logger.catching(e);
return responseFactory.getFailureResponse(e);
} catch (Exception e) {
logger.catching(e);
return responseFactory.getFailureResponse(e);
}
}
}