0

这是我的资源类:

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 ?
    }
}

动态Bean.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 :

动态BeanProvider.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);
        }
    }
}
4

1 回答 1

0

MessageBodyWriter 将起作用,或者您可以尝试使用 JAXB 注释对 DynamicBean 进行注释。但是您仍然必须有一些机制来发现属性。

更新:

我撤回了使用 JAXB 的建议:这可能比仅使用 MessageBodyWriter 涉及更多。将 Map 转换为 JSON 非常简单

于 2012-11-20T10:38:52.443 回答