Java 基本资源返回类型的JAX-RS自定义JSON表示
假设我们有一个具有以下合同的服务:Java 基本资源返回类型的JAX-RS自定义JSON表示,java,jakarta-ee,jax-rs,Java,Jakarta Ee,Jax Rs,假设我们有一个具有以下合同的服务: public interface CategoryService { public int createNew(String languageCode, String name, String descriptionMarkdown, Integer parentCategoryID, String createdByUserName) throws ServiceException; }; 如何映射int返回类型以生成如下所示的JSON值 PS
public interface CategoryService {
public int createNew(String languageCode, String name, String descriptionMarkdown, Integer parentCategoryID, String createdByUserName) throws ServiceException;
};
如何映射int
返回类型以生成如下所示的JSON值
PS:我知道createNew
方法必须是HTTP POST请求(注释@POST
)。假设有注释。我只需要回复
{"id": 1}
不知道这是不是个好主意。如果您将创建新的JAX-RS资源和指定的实体类来进行响应,则会更好。
不过,如果您想将编组与模型混合使用,您可以编写自己的MessageBodyWriter。例如:
@Produces("application/json")
public class IntWriter implements MessageBodyWriter<Integer> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
boolean intAsID = false;
for (Annotation a : annotations) {
if (a.annotationType().getCanonicalName().equals("com.blabla.IntAsID")) {
intAsID = true;
break;
}
}
return intAsID && (type == Integer.class);
}
@Override
public long getSize(Integer integer, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return 0;
}
@Override
public void writeTo(Integer integer, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
JsonGenerator generator = Json.createGenerator(entityStream);
generator.writeStartObject()
.write("id", integer)
.writeEnd()
.flush();
}
}
不要忘记设置正确的保留策略。并检查isWriteable
方法中是否存在此注释。就像我在示例中所做的那样。是的,将此注释添加到您的资源中:
public interface CategoryService {
@IntAsID
public int createNew(String languageCode, String name, String descriptionMarkdown, Integer parentCategoryID, String createdByUserName) throws ServiceException;
};
三,
使用@生成注释。这将有助于您的JAX-RS提供程序在资源应该生成JSON而不是JSON的情况下不检查此编写器。
四,
不要关心getSize()
方法。其结果现在被忽略(至少在泽西岛是如此)。
五,
不要在writeTo
方法中关闭entityStream
。
是否要求返回类型int
?目前,是的,因为它是EJB3.x中使用的接口。CategoryResource
类是实现此接口的JAX-RS类。JBoss Wildfly 8.2.0-Final不使用Jersey作为JAX-RS实现。它使用RESTEasy作为JAX-RS实现。我忘了声明该项目完全依赖于JAX-RS规范,而不是特定于第三方的,因为它将在不同的容器上运行。@BuhakeSindi据我所知,MessageBodyWriter是JAX-RS的一部分,而不是特定于Jersey的。ResourceConfig
是特定于Jersey的。@BuhakeSindi哦,当然。稍后我会在PC附近重写它。如果需要,您可以从应用程序继承(ResourceConfig从其继承):它是JAX-RS的一部分,工作方式相同。@BuhakeSindi好的,我重写了它。现在它应该是纯JAX-RS。
@Retention(RetentionPolicy.RUNTIME)
public @interface IntAsID {}
public interface CategoryService {
@IntAsID
public int createNew(String languageCode, String name, String descriptionMarkdown, Integer parentCategoryID, String createdByUserName) throws ServiceException;
};