On Sep 25, 2009, at 8:16 PM, Herak Sen wrote:
> 1) Jersey does not provide a MessageBodyWriter for Maps. You
> can write a custom MessageBodyWriter.
> 2) JAXB- does not support Maps as top level object, so another
> solution is to write adaptor for Map
>
>
> e.g
> MessageBodyWriter
>
> @Provider
> public class MapMessageWriter implements
> MessageBodyWriter<HashMap<String, String>>{
>
> @Override
> public long getSize(HashMap<String, String> t, Class<?> type,
> Type genericType, Annotation[] annotations,
> MediaType mediaType) {
> // TODO Auto-generated method stub
> return -1;
> }
>
> @Override
> public boolean isWriteable(Class<?> type, Type genericType,
> Annotation[] annotations, MediaType mediaType) {
This method also needs to check that the type is of HashMap<String,
String>.
Paul.
>
> return
> mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE);
> }
>
> @Override
> public void writeTo(HashMap<String, String> t, Class<?> type,
> Type genericType, Annotation[] annotations,
> MediaType mediaType,
> MultivaluedMap<String, Object> httpHeaders,
> OutputStream entityStream) throws IOException,
> WebApplicationException {
>
> // Simple marshalling
> StringBuffer sb = new StringBuffer("<map>");
> for (Map.Entry<String, String> entry : t.entrySet()) {
> sb.append("<entry>");
> sb.append("
> <key>").append(entry.getKey()).append("</key>");
> sb.append("
> <value>").append(entry.getValue()).append("</value>");
> sb.append("</entry>");
> }
> sb.append("</map>");
> System.out.println(sb);
> entityStream.write(sb.toString().getBytes());
> }
>
> }
>
> Adaptor
>
> @XmlRootElement
> class Entry {
> public String key;
>
> public String value;
>
> public Entry() {}
> public Entry(Map.Entry<String,String> e) {
> key = e.getKey();
> value = e.getValue();
> }
> }
> @GET
> @Produces("application/xml")
> public List<Entry> getAttributes() {
> Map<String, String> map = new HashMap<String, String>();
> map.put("k1", "v1");
> map.put("k2", "v2");
> List<Entry> entry = new ArrayList<Entry>();
> for( Map.Entry<String,String> e : map.entrySet() )
> entry.add(new Entry(e));
> return entry;
> }
>
> Hope this helps
>
> Herak
>
> From: Saavedra, Gisella [mailto:gsaavedra_at_zebra.com]
> Sent: Friday, September 25, 2009 12:55 PM
> To: users_at_jersey.dev.java.net
> Subject: [Jersey] REST service returning Map collection
>
>
> Can somebody point me to an example or article, if it exists,
> containing a code snippet returning a Map collection, something like
> @GET
> @Produces({"application/xml"})
> public Map<String, String> getAttributes(…) { }
>
>
> just receiving a Map object at the client side, or returning an
> object that contains the Map?
> No JSON.
>
> I will appreciate it.
>
> Thanks.
>
> Gisella Saavedra
> Sr. Software Engineer
> gsaavedra_at_zebra.com
> <image001.gif>
> 1000 Broadway, Suite 150, Oakland, CA 94607 | T+1 510 267 5123 T
> Main+1 510 267 5000 F+1 510 267 5100 | http://www.zebra.com/zes
>
>
>