これが私のリソースクラスです:
DynamicBeanResource.java
@Path("/")
public class DynamicBeanResource {
@GET
@Path("/{entity}.xml/{id}")
@Produces(MediaType.APPLICATION_XML)
public DynamicBean getAsXML(@PathParam("entity") String entity, @PathParam("id") String id) {
//Retrieve bean
DynamicBean b=getDynamicBean();
// How can I tell Jersey how to find the properties of the bean ?
}
@GET
@Path("/{entity}.json/{id}")
@Produces(MediaType.APPLICATION_JSON)
public DynamicBean getAsJSON(@PathParam("entity") String entity, @PathParam("id") String id) {
//Retrieve bean
DynamicBean b=getDynamicBean();
// How can I tell Jersey how to find the properties of the bean ?
}
}
DynamicBean.java
public class DynamicBean {
Map<String,String> properties;
// Contructor...
public String getProperty(String name) throws UnknownPropertyException {
// Get the property from the Map and returns it
}
public void setProperty(String name, String value) throws UnknownPropertyException {
// Updates the property into the Map
}
}
編集
この問題を解決するために、私は自分のMessageBodyWriterを作成しました。
DynamicBeanProvider.java
@Provider
@Produces({ MediaType.APPLICATION_XHTML_XML })
public class DynamicBeanProvider implements MessageBodyWriter<DynamicBean> {
@Override
public boolean isWriteable(Class<?> clazz, Type paramType, Annotation[] paramArrayOfAnnotation, MediaType paramMediaType) {
return DynamicBean.class.isAssignableFrom(clazz);
}
@Override
public long getSize(DynamicBean paramT, Class<?> paramClass, Type paramType, Annotation[] paramArrayOfAnnotation,
MediaType paramMediaType) {
return -1;//-1 indicates it's not possible to determine the size in advance
}
@Override
public void writeTo(DynamicBean bean, Class<?> paramClass, Type paramType, Annotation[] paramArrayOfAnnotation,
MediaType mt, MultivaluedMap<String, Object> paramMultivaluedMap, OutputStream out) throws IOException,
WebApplicationException {
if (bean == null) {
throw new WebApplicationException(Status.NOT_FOUND);
}
String ret = null;
if (mt.equals(MediaType.APPLICATION_XHTML_XML_TYPE)) {
ret = convertDynamicBeanToXHTML(bean);
}
if (ret != null) {
out.write(ret.getBytes(Charset.forName("UTF-8")));
} else {
throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
}
}
}